O'Reilly logo

Études for Elixir by J. David Eisenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required