Elixir Koans - 10 Structs
defmodule Person do
@ moduledoc false
defstruct [ :name , :age ]
end
Structs are defined and named after a module
Unless previously defined, fields begin as nil
You can pass initial values to structs
joe = % Person { name: "Joe" , age: 23 }
Update fields with the cons '|' operator
joe = % Person { name: "Joe" , age: 23 }
older = % { joe | age: joe . age + 10 }
Struct can be treated like maps
silvia = % Person { age: 22 , name: "Silvia" }
assert Map . fetch ( silvia , :age ) == ___
Use the put_in macro to replace a nested value
defmodule Plane do
@ moduledoc false
defstruct passengers: 0 , maker: :boeing
end
defmodule Airline do
@ moduledoc false
defstruct plane: % Plane { } , name: "Southwest"
end
assert put_in ( airline . plane . maker , :airbus ) == ___
Use the update_in macro to modify a nested value
airline = % Airline { plane: % Plane { passengers: 200 } }
assert update_in ( airline . plane . passengers , fn x -> x + 2 end ) == ___
Use the put_in macro with atoms to replace a nested value in a non-struct
airline = % { plane: % { maker: :boeing } , name: "Southwest" }
assert put_in ( airline [ :plane ] [ :maker ] , :cessna ) == ___