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
@moduledocdocuments the module;@c_km_sand friends store values at compile time.- Underscores group digits, so
299_792and225_000_000read at a glance. delay_sdivides round-trip distance by light speed andFloat.roundtrims the answer.
Keywords and builtins used here
FloatIOOrbitdefdefmoduledoend
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.
Step 3 of 3 in Modules & functions, step 3 of 27 in Language basics.