Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading