CamelBak
CamelBak

Reputation: 105

Function does not work when I call it in an other function

import Data.List (sort,nub,(\\),transpose,genericLength)
import Data.String (lines,unlines)


type Row a    = [a]
type Matrix a = [Row a]
type Digit    = Char

digits :: [Digit]
digits = ['1'..'9']

blank :: Digit -> Bool
blank d = d == ' '

-- 1.
group :: [a] -> [[a]]
group = groupBy 3

groupBy :: Int -> [a] -> [[a]]
groupBy _ [] = [] 
groupBy n xs = let (ys, zs) = splitAt n xs
               in  ys : groupBy n zs

-- 2.
intersperse :: a -> [a] -> [a]
intersperse x y = x : [ x | ys <- y, x <- [ys, x]]

-- 3.
showRow :: String -> String
showRow xs = intersperse "|" (groupBy 3 xs)

Error Message Below

Tutorial9.hs:35:14: error:
    • Couldn't match type ‘[Char]’ with ‘Char’
      Expected type: String
        Actual type: [[Char]]
    • In the expression: intersperse "|" (groupBy 3 xs)
      In an equation for ‘showRow’:
          showRow xs = intersperse "|" (groupBy 3 xs)
   |
35 | showRow xs = intersperse "|" (groupBy 3 xs)
   |   

       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The group function works well, but doesn't seem to work when I call it in showRow. Why?

Upvotes: 1

Views: 67

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

The intersperse :: a -> [a] -> [a]** will return a [String] not a String, since groupBy 3 xs will return [String] and the separator is a String. You can make use of concat to concatenate the strings together:

showRow :: String -> String
showRow xs = concat (intersperse "|" (groupBy 3 xs))

or you can make use of intercalate :: [a] -> [[a]] -> [a], which does this already:

import Data.List(intercalate)

showRow :: String -> String
showRow xs = intercalate "|" (groupBy 3 xs)

Upvotes: 4

Related Questions