Functions and Code Organization

One of the central themes of our programs so far is that we package functions that operate on like data together in a module. Let’s create a file called point.ex. We’ll have functions on points in this module. We’ll strive to form functions that take points as the first argument of our functions, and where possible, our functions will return points as well.

Deconstruction in Function Heads

Let’s say we wanted to take a point in the form {x, y} and move it one unit to the right. Knowing that elem(tuple, index) gives us an element of the tuple, we might decide to write this bit of tedious code:

 defmodule​ Point ​do
 def​ right(point) ​do
  x = elem(point, 0)
  y = elem(point, 1)
  {x + 1, y}
 end
  ...

Get Programmer Passport: 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.