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.
精彩评论