Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Pattern Matching

Pattern Matching

Wojtek Mach

April 24, 2015
Tweet

More Decks by Wojtek Mach

Other Decks in Programming

Transcript

  1. Ranks •Straight Flush •Four of a Kind •Full House •Flush

    •Straight •Three of a Kind •Two Pairs •One Pair •High Card
  2. Conditionals Card = Struct.new :rank, :suit def rank(hand) if hand[0].rank

    == hand[1].rank && hand[0].rank == hand[2].rank && hand[0].rank == hand[3].rank :four_of_a_kind elsif hand[0].rank == hand[1].rank && hand[0].rank == hand[2].rank && hand[3].rank == hand[4].rank :full_house # ... end end
  3. OOP! Card = Struct.new :rank, :suit class Hand def four_of_a_kind?

    cards[0].rank == cards[1].rank && cards[0].rank == cards[2].rank && cards[0].rank == cards[3].rank end def full_house? # ... end # ... end
  4. Pattern matching case hand do { card1, card2, card3, card4,

    card5 } -> rank1 { card1, card2, card3, card4, card5 } -> rank2 # ... end
  5. Pattern matching case hand do { card1, card2, _ ,

    _ , card5 } -> rank1 { card1, card2, _ , _ , card5 } -> rank2 # ... end
  6. Pattern matching case hand do { {r1,s1}, {r2,s2}, _ ,

    _ , {r5,s5} } -> rank1 { {r1,s1}, {r2,s2}, _ , _ , {r5,s5} } -> rank2 # ... end
  7. Pattern matching case hand do { {a,_}, {a,_}, {a,_}, {a,_},

    _ } -> :four_of_a_kind { {a,_}, {a,_}, {a,_}, {b,_}, {b,_} } -> :full_house end
  8. Pattern matching case hand do { {a,_}, {a,_}, {a,_}, {a,_},

    _ } -> :four_of_a_kind { {a,_}, {a,_}, {a,_}, {b,_}, {b,_} } -> :full_house { {_,a}, {_,a}, {_,a}, {_,a}, {_,a} } -> :flush end
  9. Pattern matching case hand do { {a,_}, {a,_}, {a,_}, {a,_},

    _ } -> {:four_of_a_kind, a} { {a,_}, {a,_}, {a,_}, {b,_}, {b,_} } -> {:full_house, a, b} { {_,a}, {_,a}, {_,a}, {_,a}, {_,a} } -> {:flush} end
  10. Pattern matching case hand do { {a,_}, {a,_}, {a,_}, {a,_},

    _ } -> {:four_of_a_kind, a} { {a,_}, {a,_}, {a,_}, {b,_}, {b,_} } -> {:full_house, a, b} { {_,a}, {_,a}, {_,a}, {_,a}, {_,a} } -> {:flush} # straights are tricky! end