2 ms·
There's some interesting Perl 6 implementations here[1] (and in the discussion of that), which shows some interesting capabilities of multiple dispatch, and far
by kbenson 9y ago
There's some interesting Perl 6 implementations here[1] (and in the discussion of that), which shows some interesting capabilities of multiple dispatch, and farther down using subtypes along with multiple dispatch.
I particularly like this terse one:
sub fizzbuzz($n, $_ = [$n % 3, $n % 5]) {
when [0, 0] { "fizzbuzz" }
when [0, *] { "fizz" }
when [*, 0] { "buzz" }
default { $n }
}
That's fairly tight, while remaining somewhat readable. There's a version that adds a line or two by moving $_ into the body of the sub as well in case that's more readable to some.
1: https://gist.github.com/masak/b9371625ad85cfe0faba https://gist.github.com/masak/b9371625ad85cfe0faba
- laylomo 9y agoNice, reminds me of the equivalent OCaml implementation: let fizzbuzz n = match n mod 3, n mod 5 with | 0, 0 -> "fizzbuzz" | 0, _ -> "fizz" | _, 0 -> "buzz" | _ -> string_of_int n