Mike Over (2) [Avatar] Offline
#1
Listing 1.1 code is incorrect.


defmodule RaceCar do
  defstruct [:tires, :power, :acceleration, :speed]

  def accelerate(%RaceCar{speed: speed, amount: amount} = racecar) do
    Map.put(racecar, :speed, speed + amount)
  end
end

ferrari_tires = [
  %Tire{location: :front_right, kind: :racing},
  %Tire{location: :front_left, kind: :racing},
  %Tire{location: :back_right, kind: :racing},
  %Tire{location: :back_left, kind: :racing}
]
ferrari = %RaceCar{tires: ferrari_tires,
                   power: %Engine{model: "FR223"},
                   acceleration: 60,
                   speed: 0}
ferrari.speed
# => 0
RaceCar.accelerate(ferrari)
# => 60
ferrari.speed
# => 0
new_ferrari = RaceCar.accelerate(ferrari)
new_ferrari.speed
# => 60
ferrari.speed
# => 0


The accelerate function matches to a Racecar that has an "amount" key but there is no such field defined in the struct. I think what you want to do instead is:
def accelerate(%RaceCar{speed: speed, acceleration: acceleration} = racecar) do
  Map.put(racecar, :speed, speed + acceleration)
end