7. What the hell is pattern
matching and why should I
care?
Friday, April 5, 13
8. Wikipedia Definition
“...the act of checking a perceived
sequence of tokens for the presence of
the constituents of some pattern.”
Friday, April 5, 13
10. My Best Try
Checking a data type against some
predefined patterns, and when that data
type matches one of the predefined
patterns, do something.
Friday, April 5, 13
11. In Short...
Pattern matching is another way
to do control flow.
Friday, April 5, 13
31. Pretty easy, and could be implemented in
roughly the same amount of characters with
“if-then-else”
Friday, April 5, 13
32. (* Note:
hd(list) takes the first element of list
tl(list) takes all other elements of list
*)
fun sum(numbers) =
if numbers = [] then 0
else hd(numbers) + sum(tl(numbers))
Friday, April 5, 13
36. // `~` in Rust is for allocating memory
fn main() {
for int::range(1, 101) |num| {
io::println(
match (num % 3, num % 5) {
(0, 0) => ~"FizzBuzz", // must come first
(0, _) => ~"Fizz",
(_, 0) => ~"Buzz",
(_, _) => int::str(num) // must come last
}
);
}
}
// Source: Lindsey Kuper’s FizzBuzz revisited (http://composition.al/blog/2013/03/02/
fizzbuzz-revisited/)
Friday, April 5, 13
37. The real heart of the function:
match (num % 3, num % 5) {
(0, 0) => ~"FizzBuzz", // must come first
(0, _) => ~"Fizz",
(_, 0) => ~"Buzz",
(_, _) => int::str(num) // must come last
}
Friday, April 5, 13
38. That’s nice and all, but there’s more...
Friday, April 5, 13
39. Both SML and Rust are strongly typed,
and they let us define our own types.
We can then match against those types.
Friday, April 5, 13
40. enum Remainder {
zero,
other(NonZeroRem)
}
enum NonZeroRemainder {
one, two, three, four
}
Friday, April 5, 13
47. So how about Pattern Matching in Ruby?
Friday, April 5, 13
48. pattern-match
github.com/k-tsj/pattern-match
Friday, April 5, 13
49. require 'pattern-match'
match(object) do
with(pattern) do
...
end
with(pattern) do
...
end
...
end
# patterns are binded variables
available in block
Friday, April 5, 13
50. x = match(0) do
with(String) { “It’s a String!” }
with(Fixnum) { “It’s a Fixnum!” }
end
print x #=> “It’s a Fixnum!”
Friday, April 5, 13
51. require 'pattern-match'
1.upto(100) do |n|
match([(n % 3),(n % 5)]) do
with(_[0,0]) { puts "FizzBuzz" }
with(_[0,_]) { puts "Fizz" }
with(_[_,0]) { puts "Buzz" }
with(_[_,_]) { puts n }
end
end
Friday, April 5, 13
53. require 'pattern-match'
match([1, "2", 3.0, "four"]) do
with(_[a & 1, b & Or(Float, String), c & Not(Fixnum), d])
with(_[a & Fixnum, b & Not(String), c, d & Not(“four”)])
end
end
Friday, April 5, 13