开发者

Basic question on pattern matching

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].开发者_JAVA技巧
[1]
10> H.
1
11> T.
[]
12> [H|T] = [].
** exception error: no match of right hand side value []


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜