Created
August 25, 2012 02:41
-
-
Save bluegraybox/3459200 to your computer and use it in GitHub Desktop.
Cheat sheet for Erlang syntax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(cheat_sheet). % end with a period | |
%% Let these functions be called externally. | |
-export([countdown/1, countdown/0]). % number of parameters - it matters! | |
%% atoms begin with a lower-case letter | |
%% Variables begin with an upper-case letter | |
%% Start defining a function with the most specific case first | |
countdown(0) -> | |
io:format("Zero!~n"); % function clauses end with a semicolon | |
%% Another clause of the same function, with a guard expression | |
countdown(Bogus) when Bogus < 0 -> | |
io:format("Bad value: ~B~n", [Bogus]), % normal lines end with a comma | |
error; % return value (io:format returns 'ok') | |
%% Last clause matches any single parameter | |
countdown(Start) -> | |
%% case and if statements return values! | |
Type = case Start rem 2 of | |
1 -> "odd"; % case and if clauses end with semicolons | |
0 -> "even" % except the last one | |
end, % end with comma, like a normal line | |
io:format("~B is ~s~n", [Start, Type]), | |
countdown(Start - 1). % When the function is all done, end with a period | |
%% This is a different function because it has a different number of parameters. | |
countdown() -> | |
countdown(10). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ erl
Erlang R15B01 (erts-5.9.1) [source] [64-bit] [smp:4:4] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.9.1 (abort with ^G)
1> c(cheat_sheet).
{ok,cheat_sheet}
2> cheat_sheet:countdown().
10 is even
9 is odd
8 is even
7 is odd
6 is even
5 is odd
4 is even
3 is odd
2 is even
1 is odd
Zero!
ok
3> cheat_sheet:countdown(3).
3 is odd
2 is even
1 is odd
Zero!
ok
4> cheat_sheet:countdown(-2).
Bad value: -2
error
5>