Skip to content

Instantly share code, notes, and snippets.

@RyanHirsch
Created August 7, 2018 16:32
Show Gist options
  • Save RyanHirsch/89fb0bc2d4f93184a0107f1136087d26 to your computer and use it in GitHub Desktop.
Save RyanHirsch/89fb0bc2d4f93184a0107f1136087d26 to your computer and use it in GitHub Desktop.
Learn Functional Programming with Elixir - Chapter 3 Pattern Matching Tic-Tac-Toe

Create a function that returns Tic-Tac-Toe game winners. You can represent the board with a tuple of nine elements, where each group of three items is a row. The return of the function should be a tuple. When we have a winner, the first element should be the atom :winner, and the second should be the player. When we have no winner, the tuple should contain one item that is the atom :no_winner. It should work like this:

TicTacToe.winner({
:x, :o, :x,
:o, :x, :o,
:o, :o, :x
})
# {:winner, :x}
TicTacToe.winner({
:x, :o, :x,
:o, :x, :o,
:o, :x, :o
})
# :no_winner
@RyanHirsch
Copy link
Author

I am struggling to find a way to do this while keeping the tuples. I keep wanting to Tuple.to_list/1 it, then pattern match against the resulting list with multiple check/1 functions.

@podung
Copy link

podung commented Aug 7, 2018

You can pattern match with the tuples, you don't need to do the to_list first (as one option to keep the tuples)

@RyanHirsch
Copy link
Author

defmodule TicTacToe do
  def winner(board) do
    check(board)
  end

  defp check({ w, w, w, _, _, _, _, _, _ }), do: { :winner, w }
  defp check({ _, _, _, w, w, w, _, _, _ }), do: { :winner, w }
  defp check({ _, _, _, _, _, _, w, w, w }), do: { :winner, w }
  defp check({ w, _, _, w, _, _, w, _, _ }), do: { :winner, w }
  defp check({ _, w, _, _, w, _, _, w, _ }), do: { :winner, w }
  defp check({ _, _, w, _, _, w, _, _, w }), do: { :winner, w }
  defp check({ w, _, _, _, w, _, _, _, w }), do: { :winner, w }
  defp check({ _, _, w, _, w, _, w, _, _ }), do: { :winner, w }
  defp check(_), do: { :no_winner }
end

This works but feels very brute force.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment