Haskell函数以递归方式将操作应用于参数

Jea*_*ouX 4 haskell ghc

Haskell中是否有内置函数以递归方式将参数列表应用于参数?

我有一个应用于Double(乘法,加法,...)的操作列表,我想简单地得到结果.例如 :

operationList = [
                  (\v -> v/8+2)
                , (\v -> v-12)
                , (\v -> v*v)
                ]

func operationList 3
Run Code Online (Sandbox Code Playgroud)

func应该回来92,640625.

我在hoogle搜索签名,[(a -> a)] -> a -> a但我没有找到任何东西.

Rei*_*chs 7

有(至少)两种方法来解决这个问题.一种是将每个函数应用于应用前一个函数的结果.这给你:

foldr ($) 3 (reverse operationList)
Run Code Online (Sandbox Code Playgroud)

另一种方法是首先将所有函数组合在一起,然后将结果函数应用于参数:

foldr (.) id (reverse operationList) 3
Run Code Online (Sandbox Code Playgroud)

组合下的函数的这种行为也被Endomonoid 捕获:

appEndo (foldMap Endo (reverse operationList)) 3
Run Code Online (Sandbox Code Playgroud)

必须颠倒列表,因为foldr从"从右到左"折叠:

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))
Run Code Online (Sandbox Code Playgroud)


beh*_*uri 5

\> foldr ($) 3 (reverse operationList)
92.640625
Run Code Online (Sandbox Code Playgroud)

要么

\> foldl (flip ($)) 3 operationList
92.640625
Run Code Online (Sandbox Code Playgroud)