I know that you can do matching on lists in a way like
val list = List(1,2,3)
list match {
case head::tail => head
case _ => //whatever
}
so I started to wonder how this works. If I understand correctly, :: is just an operator, so what’s to stop me from doing something like
4 match {
case x + 2 => x //I would expect x=2 here
}
If there is a way to create this kind of functionality, how is it done; if not, then why?
Pattern matching takes the input and decomposes it with an
unapplyfunction. So in your case,unapply(4)would have to return the two numbers that sum to 4. However, there are many pairs that sum to 4, so the function wouldn’t know what to do.What you need is for the
2to be accessible to theunapplyfunction somehow. A special case class that stores the2would work for this:(It would be nice to be able to do something like
val Sum(2)(y) = 5for compactness, but Scala doesn’t allow parameterized extractors; see here.)[EDIT: This is a little silly, but you could actually do the following too:
]
EDIT: The reason the
head::tailthing works is that there is exactly one way to split the head from the tail of a list.There’s nothing inherently special about
::versus+: you could use+if you had a predetermined idea of how you wanted it to break a number. For example, if you wanted+to mean “split in half”, then you could do something like:and use it like:
EDIT: Finally, this explains that, when pattern matching,
A op Bmeans the same thing asop(A,B), which makes the syntax look nice.