Reputation: 35
I have this encode function:
class Encode a where
encode :: a -> [Bit]
and I have problems writing a function that encodes a list of type a to a list of bits. I want to recursively encode the elements of a list. In my understanding you can use the map function for that purpose. The problem is that encode returns a list [Bit], whereas map expects just Bit. How can I solve this? Here is the relevant part of the program.
instance Encode a => Encode [a] where
encode [] = [I, O, O, I, O, I]
encode m = ([I, O, O] ++ (map encode m) ++ [I, O, I])
Upvotes: 0
Views: 573
Reputation: 47072
Use concatMap
. It concat
enates the results after map
ping them.
instance Encode a => Encode [a] where
encode [] = [I, O, O, I, O, I]
encode m = ([I, O, O] ++ (concatMap encode m) ++ [I, O, I])
How you could have found this out for yourself: if you search for the type of the function you want, (a -> [Bit]) -> [a] -> [Bit]
, using Hoogle, concatMap
is the first result.
Upvotes: 6