模式匹配的基本问题
我注意到 [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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
[H|T]
将[]
与H=T=[]
匹配,则[[]] 与
[]
区分开来。此外,模式
[]
和[H|T]
将不再是互斥的,因此如果您不小心先匹配了[H|T]
在递归函数中,其中[]
是基本情况,您会导致无限递归。另外,使用
[]
作为“此列表没有头部”的符号似乎很随意,可能会让很多用户感到惊讶。If
[H|T]
would match[]
withH=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.虽然 @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.