折叠Haskell中的功能列表

我正在尝试编写一个函数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进行此操作的最佳方法是什么? 谢谢!

qzrobinh 回答:折叠Haskell中的功能列表

带有折叠的应该是:

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
本文链接:https://www.f2er.com/3148167.html

大家都在问