Reputation: 23
I'm trying to create a run-length encoding function in Haskell. I know there are lot's of examples out there, I'm not really looking for a solution but more for an explanation why mine doesn't work.
rle [] s acc = acc
rle (x:xs) s acc = rle xs s ((x, count x s) : acc)
count x = length . filter (x==)
For some reason Haskell isn't able to pattern match this.
e.g. rle "abcd" "aaa" []
should return [('a',3),('b',0),...]
but always causes a Non-exhaustive patterns Exception.
Am I missing something obvious here?
Upvotes: 1
Views: 117
Reputation: 476624
I assume that you defined this in ghci
. If you write functions that span multiple lines, you should surround these by :{
and :}
. If you do not do that, you define two functions rle
. The second one will be more locally scoped, hence if you later call rle
, it will pick that one.
For example:
$ ghci
GHCi, version 8.0.2: http://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /home/kommusoft/.ghci
Prelude> :{
Prelude| rle [] s acc = acc
Prelude| rle (x:xs) s acc = rle xs s ((x, count x s) : acc)
Prelude|
Prelude| count x = length . filter (x==)
Prelude| :}
Prelude> rle "abcd" "aaa" []
[('d',0),('c',0),('b',0),('a',3)]
Working with count
will however not work here, since your rle
each time makes one step in the list. Furthermore you here do not need to use an accumulator.
Upvotes: 2