What do I return for an empty list on a question about functions?

This is the exercise in question

Define the function
compose :: [a → a] → (a → a), which composes a list of functions
into a single function, so, for example:
compose [f0,f1,f2] x = f0 (f1 (f2 x))

What I have coded up looks like this

compose :: [a -> a] -> (a -> a)
compose (f:fs) = f . (compose fs)

Now I need something to return for if the argument [a -> a] is empty, but I don’t know what. So for case compose [].

Thanks in advance!

>Solution :

You use id, it will map the element on itself. This would also be the neutral element in a monoid you can build over functions:

compose :: [a -> a] -> (a -> a)
compose [] = id
compose (f : fs) = f . (compose fs)

your function is equivalent to:

compose :: Foldable f => f (a -> a) -> a -> a
compose = foldr (.) id

Leave a Reply