Reading/practicing through “Functional Web Development with Elixir, OTP and Phoenix”, I came across the following module definition;
defmodule IslandsEngine.Rules do
alias __MODULE__
defstruct state: :initialized,
player1: :islands_not_set,
player2: :islands_not_set
def new(), do:
%Rules{}
def check(%Rules{state: :initialized} = rules, :add_player), do:
{:ok, %Rules{rules | state: :players_set}}
...
end
What is the reason for the first agument’s right hand side declaration (‘= rules’) is it simply a definition of the working variable within scope ?
def check(%Rules{state: :initialized} = rules, :add_player), do:
{:ok, %Rules{rules | state: :players_set}}
Running iex -S mix I see no practical difference passing in a different ‘variable’ name or direct struct, but perhaps I am missing something obvious;
Interactive Elixir (1.7.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> alias IslandsEngine.Rules
IslandsEngine.Rules
iex(2)> things = Rules.new()
%IslandsEngine.Rules{
player1: :islands_not_set,
player2: :islands_not_set,
state: :initialized
}
iex(3)> Rules.check(things, :add_player)
{:ok,
%IslandsEngine.Rules{
player1: :islands_not_set,
player2: :islands_not_set,
state: :players_set
}}
iex(4)> Rules.check(%IslandsEngine.Rules{state: :initialized}, :add_player)
{:ok,
%IslandsEngine.Rules{
player1: :islands_not_set,
player2: :islands_not_set,
state: :players_set
}}