Skip to content

Latest commit

 

History

History
110 lines (92 loc) · 3.25 KB

ch03-tuples-and-records.asciidoc

File metadata and controls

110 lines (92 loc) · 3.25 KB

Atoms, Tuples, and Pattern Matching

Note
You can learn more about working with atoms, tuples, and pattern matching in Chapter 2 of Erlang Programming, Chapter 2 of Programming Erlang, Sections 2.2 and 2.4 of Erlang and OTP in Action, and Chapters 1 and 3 of Learn You Some Erlang For Great Good!.

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

1> c(geom).
{ok,geom}
2> geom:area(rectangle, 3, 4).
12
3> geom:area(triangle, 3, 5).
7.5
4> geom:area(ellipse, 2, 4).
25.132741228718345

É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 commas to separate your guards.

Here is some sample output.

1> c(geom).
{ok,geom}
2> geom:area(rectangle, 3, 4).
12
3> geom:area(ellipse, 2, 3).
18.84955592153876
4> geom:area(triangle, 4, 5).
10.0
5> geom:area(rectangle, -1, 3).
** exception error: no function clause matching geom:area(rectangle,-1,3) (geom.erl, line 18)

Étude 3-3: Underscores

If you enter a shape that area/3 doesn’t know about, or if you enter negative dimensions, Erlang will give you an error message. Use underscores to create a catch-all'' version, so that anything at all that doesn’t match a valid rectangle, triangle, or ellipse will return zero. This goes against the Erlang philosophy of let it fail,'' but let’s look the other way and learn about underscores anyway.

Here is some sample output.

1> geom:area(rectangle, 3, 4).
12
2> geom:area(pentagon, 3, 4).
0
3> geom:area(hexagon, -1, 5).
0
4> geom:area(rectangle, 1, -3).
0

Étude 3-4: Tuples as Parameters

Add an area/1 function that takes a tuple of the form {*shape*,*number*,*number*} as its parameter. Export it instead of area/3. The area/1 function will call the private area/3 function.

Here is some sample output.

1> c(geom).
{ok,geom}
2> geom:area({rectangle, 7, 3}).
21
3> geom:area({triangle, 7, 3}).
10.5
4> geom:area({ellipse, 7, 3}).
65.97344572538566