Title here
Summary here
Here’s a basic switch
in Erlang.
-module(switch).
-export([main/0]).
main() ->
I = 2,
io:format("Write ~p as ", [I]),
case I of
1 -> io:format("one~n");
2 -> io:format("two~n");
3 -> io:format("three~n")
end,
% You can use commas to separate multiple expressions in the same case statement.
% We use the optional default case in this example as well.
case calendar:day_of_the_week(calendar:local_time()) of
6 -> io:format("It's the weekend~n");
7 -> io:format("It's the weekend~n");
_ -> io:format("It's a weekday~n")
end,
% switch without an expression is an alternate way to express if/else logic.
% Here we also show how the case expressions can be non-constants.
T = time:localtime(),
case element(4, T) < 12 of
true -> io:format("It's before noon~n");
_ -> io:format("It's after noon~n")
end,
% A type switch compares types instead of values. You can use this to discover the type of an interface value.
% In this example, the variable T will have the type corresponding to its clause.
WhatAmI = fun(I) ->
case I of
I when is_boolean(I) -> io:format("I'm a bool~n");
I when is_integer(I) -> io:format("I'm an int~n");
_ -> io:format("Don't know type ~p~n", [I])
end
end,
WhatAmI(true),
WhatAmI(1),
WhatAmI("hey").
To run the program, save the code in switch.erl
and use erl
to run it.
$ erlc switch.erl
$ erl -noshell -s switch main -s init stop
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type "hey"
Now that we can run and build basic Erlang programs, let’s learn more about the language.