Is there a built-in function in Haskell to apply a list of operations recursively to an argument?
I have a list of operations to apply to a Double
(multiplication, addition, ...) and I would like simply to get the result.
For example :
operationList = [
(\v -> v/8+2)
, (\v -> v-12)
, (\v -> v*v)
]
func operationList 3
func
should return 92,640625
.
I searched in hoogle the signature [(a -> a)] -> a -> a
but I didn't find anything.
There are (at least) two ways to solve this problem. One is to apply each function to the result of applying the previous function. This gives you:
foldr ($) 3 (reverse operationList)
The other is to first compose all the functions together and then to apply the resulting function to the argument:
foldr (.) id (reverse operationList) 3
This behavior of functions under composition is also captured by the Endo
monoid:
appEndo (foldMap Endo (reverse operationList)) 3
The list must be reversed because foldr folds from "right to left":
foldr ($) 3 [f,g,h]
= { definition of foldr }
f $ g $ h $ 3
= { definition of ($) }
f (g (h 3))
foldr (.) id [f,g,h] 3
= { definition of foldr }
(f . g . h . id) 3
= { definition of (.), definition of id, eta reduction }
f (g (h 3))
\> foldr ($) 3 (reverse operationList)
92.640625
or
\> foldl (flip ($)) 3 operationList
92.640625
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With