Haskell中函数列表上的Foldl
我正在尝试编写一个函数,Haskell中函数列表上的Foldl,haskell,foldleft,Haskell,Foldleft,我正在尝试编写一个函数,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
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
另一个预计到达时间:
pipe :: [(a -> a)] -> (a -> a)
pipe = foldl (.) id
以你为例:
pipe [(\x -> x * 4), (\x -> x + x)] 3
=> 24
管道实际上可以比你想象的简单得多,而且没有必要使用效率相当低的foldl
(即使在你自己的括号中也可以看到它们是正确关联的):只需翻转(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
你认为foldLeft
和base
应该是什么?你完全没有直觉吗?PS函数名为foldl
,没有foldLeft
这样的东西。(虽然我不得不考虑一下,但我不相信这对左折叠会起到预期的作用——在哈斯克尔,使用右折叠通常更自然。)我对哈斯克尔很陌生——但想象一下,foldLeft和foldl是一样的。写下f
和base
必须具备的类型,就知道从哪里开始了。(我无意中在我上述评论的第一句话中写下了foldLeft
,我的意思是f
),这应该使它们应该是什么变得相当明显。我认为base
应该是fs
。我已经在我的帖子中添加了功能的预期结果f
应该是一个函数,它以某种方式将上一个术语的函数与“fs”堆叠在一起。我可能离这里很远,我很迷茫。我知道你想要这个函数做什么(而且foldl
和foldr
,我检查过了)。但是base
不能是fs
,因为它们有不同的类型。认真地写下f
和base
的类型,这会让事情更清楚。你会惊讶地发现,只要确保类型匹配,你就能和Haskell走得多远。思考base
的另一种方式是:如果给定一个空列表,您希望pipe
做什么?