Skip to content

Instantly share code, notes, and snippets.

@moritz

moritz/multi.p6 Secret

Created August 5, 2012 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritz/c7dc535fe2900ff0b75f to your computer and use it in GitHub Desktop.
Save moritz/c7dc535fe2900ff0b75f to your computer and use it in GitHub Desktop.
"Using Perl 6" multid dispatch example
class Rock { }
class Paper { }
class Scissors { }
multi wins(Scissors $, Paper $) { +1 }
multi wins(Paper $, Rock $) { +1 }
multi wins(Rock $, Scissors $) { +1 }
multi wins(::T $, T $) { 0 }
multi wins( $, $) { -1 }
sub play ($a, $b) {
given wins($a, $b) {
when +1 { say "Player One wins" }
when 0 { say "Draw" }
when -1 { say "Player two wins" }
}
}
play(Rock, Rock); # output: Player two wins
given wins(Rock, Rock) {
when +1 {say "Player One wins"}
when 0 {say "Draw"}
when -1 { say "Player two wins"}
} # output: Draw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment