Haskell 递归地将操作应用于参数的函数
Haskell function to apply operations recursively to an argument
Haskell 中是否有内置函数可以递归地将操作列表应用于参数?
我有一个应用于 Double
的操作列表(乘法、加法...),我只想得到结果。
例如:
operationList = [
(\v -> v/8+2)
, (\v -> v-12)
, (\v -> v*v)
]
func operationList 3
func
应该 return 92,640625
.
我在 hoogle 中搜索了签名 [(a -> a)] -> a -> a
但我没有找到任何东西。
\> foldr ($) 3 (reverse operationList)
92.640625
或
\> foldl (flip ($)) 3 operationList
92.640625
有(至少)两种方法可以解决这个问题。一种是将每个函数应用于应用前一个函数的结果。这给你:
foldr ($) 3 (reverse operationList)
另一种是先将所有函数组合在一起,然后将结果函数应用于参数:
foldr (.) id (reverse operationList) 3
组合下函数的这种行为也被 Endo
幺半群捕获:
appEndo (foldMap Endo (reverse operationList)) 3
必须反转列表,因为 foldr 从 "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))
Haskell 中是否有内置函数可以递归地将操作列表应用于参数?
我有一个应用于 Double
的操作列表(乘法、加法...),我只想得到结果。
例如:
operationList = [
(\v -> v/8+2)
, (\v -> v-12)
, (\v -> v*v)
]
func operationList 3
func
应该 return 92,640625
.
我在 hoogle 中搜索了签名 [(a -> a)] -> a -> a
但我没有找到任何东西。
\> foldr ($) 3 (reverse operationList)
92.640625
或
\> foldl (flip ($)) 3 operationList
92.640625
有(至少)两种方法可以解决这个问题。一种是将每个函数应用于应用前一个函数的结果。这给你:
foldr ($) 3 (reverse operationList)
另一种是先将所有函数组合在一起,然后将结果函数应用于参数:
foldr (.) id (reverse operationList) 3
组合下函数的这种行为也被 Endo
幺半群捕获:
appEndo (foldMap Endo (reverse operationList)) 3
必须反转列表,因为 foldr 从 "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))