haskell - haskell 如何以 head 函数的模式打破列表

标签 haskell pattern-matching

在学习 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
headtail指针未初始化,因为它们没有被使用。当你写 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/

相关文章:

list - 避免不完整的模式匹配

R:改进嵌套 ifelse 语句和多种模式

列表内容的 Haskell 模式匹配

haskell 错误: parse error on input '='

list - 列表的 Haskell 连续子列表

在 Haskell 中循环 Unboxed 数组的性能

android.util.Patterns.EMAIL_ADDRESS 正在验证无效的电子邮件

http - 在 Haskell 中寻找一个允许将 Web 响应主体作为流使用的包

haskell - 并发程序中IORef操作重排序的推理

list - Haskell 模式匹配出错