这个由`foldr`实现的`++`是如何工作的?

时间:2017-03-12 10:15:57

标签: haskell functional-programming fold

我正在通过Channel 9 Lectures中的haskell 中的编程来学习Haskell。在第7章中,教授使用++通过

实现了自己的foldr运算符
(++ ys) = foldr (:) ys

他的推理是

  xs ++ ys = foldr (:) ys xs
= (++) ys xs = foldr (:) ys xs
= (++ ys) = foldr (:) ys

这是黑板

enter image description here

我在这里感到困惑,为什么xs ++ ys的功能与(++) ys xs相同。我让xs = [1,2,3]ys = [4,5,6]由runhaskell运行,他们只会产生不同的答案:

> main = print $ [1,2,3] ++ [4,5,6]
[1,2,3,4,5,6]
> main = print $ foldr (:) [4,5,6] [1,2,3]
[1,2,3,4,5,6]
> main = print $ (++) [4,5,6] [1,2,3] 
[4,5,6,1,2,3]

那么教授在他的推理中究竟是什么意思?

顺便说一下,我试图像以下一样自己诱导:

  xs ++ ys = foldr (:) ys xs
= (++) xs ys = foldr(:) ys xs
方程右侧的

foldr(:) ys xs表示此y Foldable中的每个ys,将:应用于y和{ {1}},这实际上是左侧所做的。我的推理是对的吗?

1 个答案:

答案 0 :(得分:4)

IMO,你的推理是正确的 - 视频中有错误:

xs ++ ys = ...
= (++) ys xs = ...

应该是

xs ++ ys = ...
= (++) xs ys = ...

如果您查看video的评论,您会注意到Tom Lokhorst pointed out this error (among several others)