1
votes

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
1
This works fine (as in "it type checks", as it will remove all except the t lines). Did you accidentally use =='t' instead of == "t" in your original code?Zeta
whoops, it originally was just 't'. I tried "t" but the problem I had with "t" is it filters out everything so the list becomes emptysanic
@shamu11 Not everything, just all lines that are not "t".melpomene
That's because filter p … will throw away ever x where p x is False, e.g. every line that's not "t".Zeta
so how do I just remove a "t" from each element in the list and the the whole line?sanic

1 Answers

3
votes

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').