Write a module with a function that takes the length and width of a rectangle and returns (yields) its area. Name the module Geom, and name the function area. Save the module in a file named geom.ex. The function has arity 2, because it needs two pieces of information to make the calculation. In Elixir-speak: write function area/2.
Here is some sample output.
iex(1)> c("geom.ex") [Geom] iex(2)> Geom.area(3,4) 12 iex(3)> Geom.area(12, 7) 84
Modify the function you wrote in Étude 2-1 so that the default variables for the length and width are 1. Here is some sample output.
iex(1)> c("geom.ex") [Geom] iex(2)> Geom.area(7, 5) 35 iex(3)> Geom.area(7) 7 iex(4)> Geom.area() 1
Document the Geom module and area function that you wrote in Étude 2-2. See a suggested solution in Appendix A.
What happens if you have default values that aren’t the last ones in the function definition? Try it and find out. Enter this code into a file named test.ex
defmodule Test do def sum( a \\ 3, b, c \\ 7) do a + b + c end end
See what happens when you try the following in iex (remember to compile the file first).
Test.sum(11, 22, 33) Test.sum(11, 22) Test.sum(11)