Answers for Chapter 3, Using Pattern Matching to Control the Program Flow

  • Here’s the function that calculates the total points spent in attributes:

     defmodule​ CharacterAttributes ​do
     def​ total_spent(%{​strength:​ str, ​dexterity:​ dex, ​intelligence:​ int}) ​do
      (str * 2) + (dex * 3) + (int * 3)
     end
     end
  • The Tic-Tac-Toe module should be like this:

     defmodule​ TicTacToe ​do
     def​ winner({
      x, x, x,
      _, _, _,
      _, _, _
      }), ​do​: {​:winner​, x}
     
     def​ winner({
      _, _, _,
      x, x, x,
      _, _, _
      }), ​do​: {​:winner​, x}
     
     def​ winner({
      _, _, _,
      _, _, _,
      x, x, x
      }), ​do​: {​:winner​, x}
     
     def​ winner({
      x, _, _,
      x, _, _,
      x, _, _ ...

Get Learn Functional Programming with Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.