typestar

Module attributes in Elixir

Compile-time constants for a radio-delay calculator, declared once with @ and read anywhere.

defmodule Orbit do
  @moduledoc "Round-trip radio delay to nearby worlds."

  # Module attributes are constants, stamped in at compile time.
  @c_km_s 299_792
  @moon_km 384_400
  @mars_km 225_000_000

  def delay_s(km), do: Float.round(2 * km / @c_km_s, 1)

  def report do
    IO.puts("Moon, there and back: #{delay_s(@moon_km)} s")
    IO.puts("Mars, there and back: #{delay_s(@mars_km)} s")
  end
end

Orbit.report()

How it works

  1. @moduledoc documents the module; @c_km_s and friends store values at compile time.
  2. Underscores group digits, so 299_792 and 225_000_000 read at a glance.
  3. delay_s divides round-trip distance by light speed and Float.round trims the answer.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
396
Tokens
74
Three-star pace
75 tpm

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

Type this snippet

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

← Previous Next →