gpt4 book ai didi

haskell - 在 Haskell 中的函数列表中折叠

转载 作者:行者123 更新时间:2023-12-04 11:02:07 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,pipe它需要一个数学函数列表,其中 pipe [f1,...,fn] x应该返回 f1(f2(...(fn x)))我已经设置为:

pipe :: [(a -> a)] -> (a -> a)
pipe fs = foldLeft f base fs
where
f a x =
base =

-- >>> pipe [] 3
-- 3
--
-- >>> pipe [(\x -> x+x), (\x -> x + 3)] 3
-- 12
--
-- >>> pipe [(\x -> x * 4), (\x -> x + x)] 3
-- 24

使用 foldl 解决此问题的最佳方法是什么?
谢谢!

最佳答案

使用 foldl 应该是:

pipe :: [(a -> a)] -> (a -> a)
pipe fs = foldl (\rs f -> f . rs) id fs

或使用 eta:
pipe :: [(a -> a)] -> (a -> a)
pipe = foldl (\rs f -> f . rs) id

与另一个eta:
pipe :: [(a -> a)] -> (a -> a)
pipe = foldl (.) id

以你的例子为例:
pipe [(\x -> x * 4), (\x -> x + x)] 3
=> 24

关于haskell - 在 Haskell 中的函数列表中折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58740419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com