Functional pattern matching
The functional pattern matching it's an extension of the multiple dispatch feature, and allows us to call a certain function or method using values or expressions as patterns, instead of types.
Example:
1
func foo((1)) { say "one" }
2
func foo((2)) { say "two" }
3
func foo (n) { say n }
4
5
foo(1) # calls the first function
6
foo(2) # calls the second function
7
foo(3) # calls the third function
Copied!
Taking advantage of this feature, we can write the Fibonacci function in the following way:
1
func fib((0)) { 0 }
2
func fib((1)) { 1 }
3
func fib (n) { fib(n-1) + fib(n-2) }
4
5
say fib(12) # prints: 144
Copied!
In addition, instead of an expression, we can specify a block of code, which will get called with the value of the argument for checking:
1
func fib({.is_neg}) { NaN }
2
func fib({.is_zero}) { 0 }
3
func fib({.is_one}) { 1 }
4
func fib(n) { fib(n-1) + fib(n-2) }
5
6
say fib(12) # prints: 144
Copied!
For keeping the value of the argument, we can specify a parameter name in front of the block used for pattern matching:
1
func fib(n { _ <= 1 }) { n }
2
func fib(n) { fib(n-1) + fib(n-2) }
3
4
say fib(12) # prints: 144
Copied!
Pattern matching is available for methods as well:
1
class Ackermann {
2
method A({ .is_zero }, n) {
3
n + 1
4
}
5
6
method A(m, (0)) {
7
self.A(m-1, 1)
8
}
9
10
method A(m, n) {
11
self.A(m-1, self.A(m, n-1))
12
}
13
}
14
15
var obj = Ackermann()
16
say obj.A(3, 2) # prints: 29
Copied!
Last modified 1yr ago
Copy link