1 Nov 2009 03:38
Re: Question about Nil and pattern matching
On Fri, Oct 30, 2009 at 11:56 PM, jlist9 <jlist9-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
Hi, I'm having a question with Nil and pattern matching.
The following code works:
val list = List()
list match {
case Nil => "empty list"
case x :: xs => "head:" + x + ", tail:" + xs
}
But if I replace List() with Nil, I get error:
constructor cannot be instantiated to expected type; found : ::[B]
required: object Nil
It looks like Nil is not equivalent to List(). If not, how come Nil
matches List()?
If by the last line you were referring to
Nil match {
case List() => ...
}
then it may be worth mentioning that "List()" can mean one of two things. Usually it is syntactic sugar for List.apply() where List is the List singleton object (in this case not inherently related to the List class). List.apply() returns Nil, so List() eq Nil.
On the other hand when the same syntax -- List() -- appears in a case pattern match statement: an extractor, it is syntactic sugar for List.unapply, or in this case List.unapplySeq (if I'm not mistaken), which is a comparison function. List() will pattern match Nil; List(x) will pattern match a single-element List and bind its element to x; List(X) or List(`x`) will patter match on a list containing exactly X or x respectively. Similar for more elements. List(x <at> _*) will bind x to all of the list's 0 or more elements.
RSS Feed