Enno Shioji
Enno Shioji

Reputation: 26882

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

Upvotes: 3

Views: 335

Answers (2)

rvirding
rvirding

Reputation: 20916

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.

Upvotes: 0

sepp2k
sepp2k

Reputation: 370102

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.

Upvotes: 11

Related Questions