Using a List of Functions in Haskell

I wrote a function that applies a list of functions to an element.

applyAll :: [a -> b] -> a -> [b]
applyAll [] _ = []
applyAll (f:fs) x = (f x) : (applyAll fs x)

Is there a better way to do this?

+4
source share
3 answers

This function actually already exists as a special case of a monadic function:

applyAll :: [a -> b] -> a -> [b]
applyAll = sequence
+18
source

You can use:

 applyAll l v = fmap ($ v) l

fmapraises a function above an input list (virtually any Functor). $has a type (a -> b) -> a -> b, so it applies the function to the given value. ($ v)is a section that applies this function to v.

+8
source

- , , , , :

import Control.Applicative

applyAll' fs v = fs <*> pure v

applyAll'' fs v = fs <*> [v]

This type makes things more complicated than necessary, however: we really only need an instance of Functorlists, while it applyAll'enters and immediately extracts from the instance Applicative.

+6
source

All Articles