É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(square, -1, 3).
** exception error: no function clause matching geom:area(square,-1,3) (geom.erl, line 18)

See a suggested solution in Appendix A.

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