Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell function to apply operations recursively to an argument

Tags:

haskell

ghc

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.

like image 230
JeanJouX Avatar asked Dec 15 '22 12:12

JeanJouX


2 Answers

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))
like image 148
Rein Henrichs Avatar answered May 17 '23 01:05

Rein Henrichs


\> foldr ($) 3 (reverse operationList)
92.640625

or

\> foldl (flip ($)) 3 operationList
92.640625
like image 24
behzad.nouri Avatar answered May 17 '23 03:05

behzad.nouri