Chapter 2. Functions and Modules

Étude 2-1: Writing a Function

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

See a suggested solution in Appendix A.

Étude 2-2: Writing a Function with Default Values

Modify the function you wrote in Étude 2-2 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

Étude 2-3: Documenting a Module

Document the Geom module and area function that you wrote in Étude 2-2. See a suggested solution in Appendix A.

Étude 2-4: Discovery Étude

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)

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.