0

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])

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You don't even need to special-case the empty list, @user2367390, it's also covered by the second equation.
Following up on the comment about Hoogle--a useful approach to such situations is to put a custom function in place, define it with undefined, and then use ghci to find the type (:t function). That shows you the type the compiler infers; that can help writing the function, or you can search for the signature with Hoogle. (Here that would mean defining encode m = ([I, O, O] ++ (map' encode m) ++ [I, O, I]) and map' = undefined; loading in ghci and typing :t map').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.