模式匹配的基本问题

发布于 2024-10-18 09:15:52 字数 312 浏览 1 评论 0原文

我注意到 [H|T] = [1]. 成功,但 [H|T] = []. 失败。我想这就是它的工作原理,但是设计者有什么原因没有选择让这个模式匹配成功并导致分配 H=[]T=[]< /代码>?

9> [H|T] = [1].
[1]
10> H.
1
11> T.
[]
12> [H|T] = [].
** exception error: no match of right hand side value []

I noticed that [H|T] = [1]. succeeds but [H|T] = []. fails. I guess that's just how it works, but is there any reason the designer didn't chose to let this pattern matching succeed and result in assignment of H=[] and T=[]?

9> [H|T] = [1].
[1]
10> H.
1
11> T.
[]
12> [H|T] = [].
** exception error: no match of right hand side value []

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

潜移默化 2024-10-25 09:15:52

如果 [H|T][]H=T=[] 匹配,则 [[]] 与 [] 区分开来。

此外,模式 [][H|T] 将不再是互斥的,因此如果您不小心先匹配了 [H|T]在递归函数中,其中 [] 是基本情况,您会导致无限递归。

另外,使用 [] 作为“此列表没有头部”的符号似乎很随意,可能会让很多用户感到惊讶。

If [H|T] would match [] with H=T=[], then [[]] would not be distinguishable from [] using pattern matching.

Further the patterns [] and [H|T] would no longer be mutually exclusive, so if you accidentally matched [H|T] first in a recursive function, where [] is the base case, you'd cause infinite recursion.

Also using [] as a symbol for "this list does not have a head" seems quite arbitrary and might surprise a lot of users.

余厌 2024-10-25 09:15:52

虽然 @sepp2k 所说的是正确的,但 [] 不匹配 [_|_] 的更根本原因是它们是不同的数据类型,因此不应该匹配。它会破坏模式匹配的要点。

While what @sepp2k says is correct, a more fundamental reason for [] not to match [_|_] is that they are different data types and so should not match. It would defeat the point of pattern matching.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文