在学习 Haskell 时,我无法理解 Haskell 如何自动匹配提取列表头部的模式。
head' :: [a] -> a
head' [] = error "Can't find head in an Empty list!"
-- How does haskell break the list into x(first) and xs(rest)?
head' (x:xs) = x
我读过 [1,2,3]
是 1:2:3:[]
的语法糖.所以
:
是一个接受任何参数并添加到右手参数的函数?列表是如何向后分解成两个变量 head 和 rest 的?
[1,2,3] --> (x:xs)
??colon_operator :: a -> [a]
-- not sure how the function would look
对不起,如果我不能简洁地解释我的问题,我在 haskell 方面并不是那么好。
最佳答案
警告讲师:这是第零个近似值,在很多方面都是错误的,但至少它是第零个近似值!
使用伪代码,当您调用 []
时或 :
,创建了一个新的数据结构。以下是用命令式语言编写结构的方法:
structure {
int constructor
ptr head
ptr tail
} list
当你写 empty = []
,即分配一个新的 list
,并以这种方式填充它:empty = alloc(list)
empty.constructor = 0 // 0 means we used [] to construct this
head
和 tail
指针未初始化,因为它们没有被使用。当你写 not_empty = 3 : [4]
,即分配一个新的 list
,并以这种方式填充它:// three is a pointer to 3
// four is a pointer to [4]
not_empty = alloc(list)
not_empty.constructor = 1 // 1 means we used : to construct this
not_empty.head = three
not_empty.tail = four
现在,当您对列表进行模式匹配时,相当于检查 constructor
field 。所以如果你写,说:case not_empty of
[] -> 7
x:xs -> 20 + x
那么命令式发生的事情是这样的:if not_empty.constructor == 0
return 7
elseif not_empty.constructor == 1
return 20 + dereference(not_empty.head)
endif
(同样,如果您提到 xs
,它会取消引用 tail
指针。)建间
list
结构和模式匹配,您现在知道用于在列表上构建每个函数的基本构建块!在最基本的层面上,只有这两个 list
- 你可以做的事情。
关于haskell - haskell 如何以 head 函数的模式打破列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66083042/