Haskell: Couldn't match expected type '[a0]' with actual type '([char], [int])'

Viewed 233

My error message is as follows: ' Couldn't match expected type '[a0]' with actual type '([char], [Int])' In the first argument of 'zip'

I'm trying to do run length encoding, e.g

encode "aaaaabbbbcc"
[(’a’,5),(’b’,4),(’c’,2)]

My code is this:

encode [] = []
encode ls = zip((map head list), (map length list))
 where list = runs ls 

The 'runs' function returns [String], e.g
runs "aaaaabbbbcc"
["aaaaa","bbbb","cc"]

I don't know how to fix it, any help or explanation would be appreciated!

2 Answers

You are trying to use C-style syntax to call zip, which is interpreted as zip getting a single tuple as its argument, rather than the two lists you intended.

encode ls = zip (map head list) (map length list)
   where list = runs ls

You can do this in a single mapping where for each item of the runs ls, you map it to a 2-tuple:

encode = map (\x -> (head x, length x)) . runs

or we can rewrite the lambda expression to:

encode = map ((,) <$> head <*> length) . runs

or, as @leftroundabout says, with (&&&) :: Arrow a => a b c -> a b c' -> a b (c, c'):

import Control.Arrow((&&&))

encode = map (head &&& length) . runs
Related