对Haskell中的函数列表进行Foldl



我正试图编写一个函数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 

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

最新更新