繁体   English   中英

折叠 Haskell 中的函数列表

[英]Foldl on a list of functions in Haskell

我正在尝试编写一个 function, 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

go 关于这个使用 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 

pipe实际上可以比您想象的要简单得多,并且无需使用效率相当低的foldl (即使在您自己的括号中也可以看到 - 它们是右关联的):只需flip (foldr id) 到达那里的步骤:

pipe [f1,...,fn] x
f1 (f2 (... (fn x)))            -- your definition of pipe
id f1 (id f2 (... (id fn x)))   -- id x = x
foldr id x [f1,...,fn]          -- the definition of foldr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM