Chapter 3. Atoms, Tuples, and Pattern Matching

Étude 3-1: Pattern Matching

Use atoms and pattern matching to make your area function calculate the area of a rectangle, triangle, or ellipse. If your parameters are shape, a and b, the area for the atom :rectangle is a * b, where a and b represent the length and width. For a :triangle atom, the area is a * b / 2.0, with a and b representing the base and height of the triangle. For an :ellipse atom, the area is :math.pi() * a * b, where a and b represent the major and minor radiuses.

Here is some sample output.

iex(1)> c("geom.ex")
[Geom]
iex(2)> Geom.area(:rectangle, 3, 4)
12
iex(3)> Geom.area(:triangle, 3, 5)
7.5
iex(4)> Geom.area(:ellipse, 2, 4)
25.132741228718345

See a suggested solution in Appendix A.

Étude 3-2: Guards

Even though you won’t get an error message when calculating the area of a shape that has negative dimensions, it’s still worth guarding your area/3 function. You will want two guards for each pattern to make sure that both dimensions are greater than or equal to zero. Since both have to be non-negative, use and to separate your guards.

Here is some sample output.

iex(1)> c("geom.ex") /Users/elixir/code/ch03-02/geom.ex:1: redefining module Geom [Geom] iex(2)> Geom.area(:rectangle, -3, 4) ** (FunctionClauseError) no function clause matching: Geom.area(:rectangle, -3, 4) /Users/elixir/code/ch03-02/geom.ex:21: Geom.area(:rectangle, -3, 4) erl_eval.erl:569: :erl_eval.do_apply/6 src/elixir.erl:133: :elixir.eval_forms/3 /bin/elixir/lib/iex/lib/iex/server.ex:19: ...

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.