Appendix A. Solutions to Études

Here are the solutions that I came up with for the études in this book.

Solution 2-1

Here is a suggested solution for Étude 2-1.

geom.ex

defmodule Geom do
  def area(length, width) do
    length * width
  end
end

Solution 2-2

Here is a suggested solution for Étude 2-2.

geom.ex

defmodule Geom do
  def area(length \\ 1, width \\ 1) do
    length * width
  end
end

Solution 2-3

Here is a suggested solution for Étude 2-3.

geom.ex

defmodule Geom do
  @moduledoc """
  Functions for calculating areas of geometric shapes.

  from *Études for Elixir*, O'Reilly Media, Inc., 2013.
  Copyright 2013 by J. David Eisenberg.
  """
  @vsn 0.1

  @doc """
  Calculates the area of a rectangle, given the length and width.
  Returns the product of its arguments. The default value for
  both arguments is 1.
  """

  @spec area(number(), number()) :: number()

  def area(length \\ 1, width \\ 1) do
    length * width
  end
end

Solution 3-1

Here is a suggested solution for Étude 3-1.

geom.ex

defmodule Geom do @moduledoc """ Functions for calculating areas of geometric shapes. from *Études for Elixir*, O'Reilly Media, Inc., 2013. Copyright 2013 by J. David Eisenberg. """ @vsn 0.1 @doc """ Calculates the area of a shape, given the shape and two of the dimensions. Returns the product of its arguments for a rectangle, one half the product of the arguments for a triangle, and :math.pi times the product of the arguments for an ellipse. """ @spec area(atom(), number(), number()) :: number() def area(:rectangle, length, width) do length * width end ...

Get Études for 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.