Skip to content

Instantly share code, notes, and snippets.

@danilo-bc
Created July 22, 2021 13:11
Show Gist options
  • Select an option

  • Save danilo-bc/c6fb26a11278ef049249909eba73fadd to your computer and use it in GitHub Desktop.

Select an option

Save danilo-bc/c6fb26a11278ef049249909eba73fadd to your computer and use it in GitHub Desktop.
Julia multiple dispatch example using Rock, Paper, Scissors!
abstract type Janken end
struct Rock <: Janken end
struct Paper <: Janken end
struct Scissors <: Janken end
janken(j1::Janken, j2::Janken) = println("Same object means a tie :O!")
janken(r::Rock, p::Paper) = println("Rock is wrapped by paper :(")
janken(r::Rock, s::Scissors) = println("Rock crushes scissors!!!")
janken(p::Paper, s::Scissors) = println("Paper is cut by scissors :(")
janken(p::Paper, r::Rock) = println("Paper wraps rock!!!")
janken(s::Scissors, r::Rock) = println("Scissors is crushed by rock :(")
janken(s::Scissors, p::Paper) = println("Scissors cuts paper!!!")
# Multiple dispatch at work!
janken(Rock(), Paper())
janken(Paper(), Rock())
janken(Scissors(), Paper())
# Cases implemented by generic function
janken(Rock(), Rock())
janken(Paper(), Paper())
janken(Scissors(), Scissors())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment