Haskell: Couldn’t match type ‘Char’ with ‘[Char]’

haskell

I'm a Haskell beginner and I'm wrestling using functions to modify a list and then return it back to a string. I'm running into this error however. Any advice?

Couldn't match type 'Char' with '[Char]'

Expected type: String

Actual type: Char

createIndex:: String -> String
createIndex str = unLine (removeT (splitLines str))

splitLines:: String -> [String]
splitLines splitStr = lines splitStr

removeT:: [String] -> [String]
removeT strT = filter (=='t') strT

unLine:: [String] -> String
unLine unLinedStr = unlines unLinedStr

Best Answer

The problem is in your definition of removeT. The type of removeT is [String] -> [String], meaning it works on a list of lists of characters. Then, in your filter, you compare each list of characters (i.e., each String in the list) to a Char ('t'). This is not allowed (you cannot check values with different types for equality).

How to change your code really depends on what you intend to do. It's not entirely clear if you want to remove lines containing t's, if you want to keep lines containing t's, if you want to remove t's, or if you want to keep t's. Depending on what you want to achieve, your code will have to be modified accordingly.

Some pointers:

  • If you change the type of removeT to String -> String you can look at one line at a time. You would then have to replace removeT in the definition of createIndex by map removeT (because you're applying the function to each line)). In this case, the filter would deal with Char values so comparing with a 't' is allowed.

  • If you want to do something with lines containing t's, (== 't') is not the way to go, you will want to use ('t' `elem`) (meaning "'t' is an element of").

  • filter keeps elements matching the predicate. So if you want to remove t's from a string for example, you use filter (/= 't').

Related Topic