我正在通过Channel 9 Lectures中的haskell 中的编程来学习Haskell。在第7章中,教授使用++
通过
foldr
运算符
(++ ys) = foldr (:) ys
他的推理是
xs ++ ys = foldr (:) ys xs
= (++) ys xs = foldr (:) ys xs
= (++ ys) = foldr (:) ys
这是黑板
我在这里感到困惑,为什么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}},这实际上是左侧所做的。我的推理是对的吗?
答案 0 :(得分:4)
IMO,你的推理是正确的 - 视频中有错误:
xs ++ ys = ...
= (++) ys xs = ...
应该是
xs ++ ys = ...
= (++) xs ys = ...
如果您查看video的评论,您会注意到Tom Lokhorst pointed out this error (among several others)。