Constants in Elixir

Our program demonstrates the usage of constants. Here is the full source code.

defmodule Constants do
  def print_constants do
    # Declares a constant value
    s = "constant"
    IO.puts(s)

    # A const statement can appear anywhere a var statement can
    n = 500_000_000

    # Constant expressions perform arithmetic with arbitrary precision
    d = 3.0e20 / n
    IO.puts(d)

    # A numeric constant has no type until it’s given one, such as by an explicit conversion
    IO.puts(trunc(d))

    # A number can be given a type by using it in a context that requires one, such as a variable
    # assignment or function call. For example, here math.sin expects a float
    IO.puts(:math.sin(n))
  end
end

Constants.print_constants()

To run the program, save the code in a file with the .exs extension and execute it using the Elixir interpreter.

$ elixir constants.exs
constant
6.0e+11
600000000000
-0.28470407323754404

Now that we can run and build basic Elixir programs, let’s learn more about the language.