user2367390
user2367390

Reputation: 35

Haskell: Using map with a function that returns a list?

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

Answers (1)

dave4420
dave4420

Reputation: 47072

Use concatMap. It concatenates the results after mapping 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

Related Questions