typestar

Modules and def in Elixir

The smallest Elixir program: a module of named functions and two calls at the top level.

# defmodule groups functions; def makes them public, dot calls them.
defmodule Lighthouse do
  def greet(keeper) do
    IO.puts("Welcome to Gull Rock, #{keeper}!")
  end

  def flash(times) do
    IO.puts(String.duplicate("* ", times) <> "sweep")
  end
end

Lighthouse.greet("Ada")
Lighthouse.flash(3)

How it works

  1. defmodule Lighthouse do opens the module and def defines two public functions inside it.
  2. String.duplicate repeats the flash and <> glues "sweep" onto the end.
  3. Calls read module-dot-function: Lighthouse.greet("Ada"), then Lighthouse.flash(3).

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
285
Tokens
64
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 48 seconds.

Type this snippet

Step 1 of 3 in Modules & functions, step 1 of 27 in Language basics.

Next →