I thought I could implement n+k patterns as an active pattern in scala via unapply, but it seems to fail with unspecified value parameter: k
object NPlusK {
def apply(n : Int, k : Int) = {
n + k
}
def unapply(n : Int, k : Int) = {
if (n > 0 && n > k) Some(n - k) else None
}
}
object Main {
def main(args: Array[String]): Unit = {
}
def fac(n: Int) : BigInt = {
n match {
case 0 => 1
case NPlusK(n, 1) => n * fac(n - 1)
}
}
}
Is it possible to implement n+k patterns in Scala and in that event how?
Deconstructor unapply does not work this way at all. It takes only one argument, the matched value, and returns an option on a tuple, with as many elements as there are arguments to the your pattern (NPlusK). That is, when you have
It will look for an
unapplymethod with anInt(or supertype) argument. If there is such a method, and if the return type is aTuple2(as NPlusK appears with two arguments in the pattern), then it will try to match. Whatever subpattern there are inside NPlusK (here the variable n, and the constant 1), will not be passed to unapply in anyway (what do you expect if you writecase NPlusK(NPlusK(1, x), NPlusK(1, y))?). Instead, if unapply returns some tuple, then each element of the tuple will be matched to the corresponding subpattern, herenwhich always matches, and 1 which will match if the value is equal to 1.You could write
That would match when your
NPlusK(n, 1). But that would not matchNPlusK(n, 2), norNPlusK(1, n)(except ifnis 2). This does not make much sense. A pattern should probably have only one possible match.NPlusK(x, y)can matchnin many different ways.What would work would be something Peano integers like, with
Succ(n)matchingn+1.