Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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!

like image 568
Daan Van de Wiel Avatar asked Oct 24 '25 15:10

Daan Van de Wiel


1 Answers

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
like image 158
Willem Van Onsem Avatar answered Oct 28 '25 04:10

Willem Van Onsem