Prolog and Erlang

a side-by-side reference sheet

grammar and invocation | variables and expressions | arithmetic and logic | strings | regexes | dates and time
lists | tuples | algebraic data types | functions | execution control | file handles | files | directories
processes and environment | libraries and namespaces | reflection | repl

prolog erlang
version used
SWI Prolog 5.10 5.9
show version
$ swipl --version $ erl -version
grammar and invocation
prolog erlang
hello world $ cat ./
hello :-
  format('Hello, World!~n'),

$ swipl -q -t hello -f ./
Hello, World!
$ cat hello.erl

hello_world() ->
  io:format("Hello, World!~n"),

$ erlc hello.erl

$ erl -noshell -run hello hello_world
Hello, World!
compiler does not create a stand-alone executable:
$ erlc +native foo.erl
bytecode compiler
$ erlc foo.erl
interpreter $ cat arg-analyzer
main([String]) ->
  io:format("argument was: ~s\n", [String]);
main(_) ->
  io:format("Usage: arg-analyzer ARG\n").

$ escript arg-analyzer foo
argument was: foo
shebang $ cat arg-analyzer
#!/usr/bin/env escript
main([String]) ->
  io:format("argument was: ~s\n", [String]);
main(_) ->
  io:format("Usage: arg-analyzer ARG\n").

$ ./arg-analyzer foo
argument was: foo
$ swipl $ erl
block delimiters if ; end
case ; end
try catch end
fun ; end
receive end
statement terminator
. .
end-of-line comment
% a comment % a comment
multiple line comment /* comment line
comment line
variables and expressions
prolog erlang
variable identifier upper case letter followed by alphanumeric characters upper case letter following by alphanumeric characters and underscores.
write once variable previously unused variables on the left side of an equal sign will be assigned to values that make the left match the right
assignment X = 3.
4 = Y.
X = 3.
parallel assignment (X, Y) = (1, 2).
[X, Y] = [1, 2].
{X, Y} = {1, 2}.
foo(X, Y) = foo(1, 2).
{X, Y} = {1, 2}.
[Z, W] = [1, 2].
non-referential identifier lower case letter followed by alphanumeric characters; can also include underscore: _ lower case letter followed by alphanumeric characters; can also include period: . at-sign: @ underscore: _
quoted non-referential identifier any printable characters inside single quotes; use backslash to escape a single quote. any printable characters inside single quotes; use backslash or two single quotes to escape a single quote.
conditional expression if
  X > 0 -> 1;
  X == 0 -> X;
  X < 0 -> -1
case case X of
  1 -> true;
  0 -> false
arithmetic and logic
prolog erlang
true and false true fail true false
falsehoods false and all non-boolean values
logical operators , ; ?? ?? and or xor not
in guards:
, ;
short circuit operators andalso orelse
relational operators =:= \= < > =< >= == /= < > =< >=
no numeric conversion:
=:= =/=
arithmetic expression is(X, 2 + 2). X = 2 + 2.
arithmetic operators + - * / // mod + - * / div rem
unary negation -4 -4
integer division is(X, 7 // 3). 7 div 3.
integer division by zero zero_divisor error bad argument exception
float division is(X, 7 / 3). 7 / 3.
float division by zero zero_divisor error bad argument exception
power is(X, 2**32). math:pow(2, 32).
sqrt is(X, sqrt(2)). math:sqrt(2).
sqrt -1 arithmetic evaluation error: undefined raises bad argument exception
transcendental functions exp log sin cos tan asin acos atan atan2 math:exp math:log math:sin math:cos math:tan math:asin math:acos math:atan math:atan2
float truncation truncate round floor ceiling trunc round ?? ??
absolute value is(X, abs(-3)).
is(X, abs(-3.2)).
integer overflow
float literal with exponent 2.0e2
random number is(X, random(100)).
random seed set_random(seed(17)). random:seed(17, 17, 17).
result of not seeding seeded using /dev/random or system time interpreter uses same seed at startup.
bit operators is(X, 5 << 1).
is(X, 5 >> 1).
is(X, 5 /\ 1).
is(X, 5 \/ 1).
is(X, 5 xor 1).
is(X, 5 \ 1).
5 bsl 1
5 bsr 1
5 band 1
5 bor 1
5 bxor 1
bnot 5
binary, octal, and hex literals 2#101010
prolog erlang
string literal list of characters:
"don't say \"no\""

quoted atom:
'don\'t say "no"'
"don't say \"no\""
newline in literal yes; and \n notation can also be used yes; and \n notation can also be used
character escapes \a \b \e \f \n \r \s \t \v \xhh…\ \uhhhh \Uhhhhhhhh \ooo \\ \' \" \d is delete; \s is space
\b \d \e \f \n \q \r \s \t \u \v \xhh \x{hh…} \ooo \' \" \\
concatenate append("one ","two ",Y), append(Y,"three",X). "one " ++ "two " ++ "three"

string:concat("one ", string:concat("two ", "three"))

concatenates double quoted string literals only:
"one " "two " "three"
replicate Hbar = string:copies("-", 80).
both sides, left side, right side
string:strip(" lorem ")
string:strip(" lorem", left)
string:strip("lorem ", right)
on right, on left, both sides
string:right("lorem", 10, $ )
string:left("lorem", 10, $ )
string:centre("lorem", 10, $ )
number to string 7 + list_to_integer("12")
73.9 + list_to_float("0.039")
string to number "value: " ++ integer_to_list(8)
"value: " ++ float_to_list(3.14)
atom to string name(foo, X). atom_to_list(foo)
string to atom string_to_atom("foo", X). list_to_existing_atom("foo")
translate case
to upper, to lower
upcase_atom('lorem', X).
downcase_atom('LOREM', X).
split string:tokens("foo bar baz", " ")

{ok, Rx} = re:compile("\s+").
re:split("foo bar baz", Rx, [{return, list}])
join string:join(["foo", "bar", "baz"], " ")
character literal none $A
string length length("hello", X).

atom_length('hello', X).
index of substring
first, last
string:str("foo bar bar", bar")
string:rstr("foo bar bar", "bar")
extract substring string:substr("foo bar bar", 5, 3)
chr and ord char_code(X, 65).
char_code('A', X).
lists:nth(1, "A")
regular expressions
prolog erlang
match test {ok, Rx} = re:compile(".*1999.*").

case re:run("it's 2000", Rx) of
  {match, _} -> io:format("party!");
  nomatch -> io:format("work")
substitution {ok, Rx} = re:compile("mi").

NewStr = re:replace("do re mi mi mi", Rx, "ma",
  [global, {return,list}]).
dates and time
prolog erlang
current date/time {{YYYY,MM,DD}, {HH,MI,SS}} = calendar:universal_time().
{{YYYY,MM,DD}, {HH,MI,SS}} = calendar:local_time().
prolog erlang
list literal [1, 2, 3] [1, 2, 3]
cons X = [4 | [3, 2, 1]]. [4 | [3, 2, 1]]
head [X|_] = [1,2,3]. hd([1,2,3])
or use pattern matching:
[Head|_] = [1,2,3].
tail [_|X] = [1,2,3]. tl([1,2,3])
or use pattern matching:
[_|Tail] = [1,2,3].
length length([1,2,3], X). length([1,2,3])
append append([1,2], [3,4], List). [1,2] ++ [3,4]
sort sort([1,3,2,4], X). lists:sort([1,3,2,4]).
reverse reverse([1,2,3,4], X). lists:reverse([1,2,3,4]).
membership member(1, [1, 2, 3]).
zip lists:zip([1,2,3], ["a","b","c"]).
map lists:map(fun(X) -> X * X end, [1,2,3]).
filter lists:filter(fun(X) -> X > 2 end, [1,2,3]).
left fold lists:foldl(fun(X,Y) -> X - Y end, 0, [1,2,3,4]).
right fold lists:foldr(fun(X,Y) -> X - Y end, 0, [1,2,3,4]).
prolog erlang
tuple literal (1, "hello", 3.14) {1, "foo", 3.14}
tuple element access element(1, {1, "foo", 3.14})
setelement(2, {1, "foo", 3.14}, "bar")
tuple length tuple_size({1, "foo", 3.14})
algebraic data types
prolog erlang
function definition factorial(0,1).
factorial(N,F) :- is(N1, N - 1), factorial(N1,F1), is(F, N*F1).
factorial(0) -> 1;
factorial(N) -> N * factorial(N-1).
function definition with guards factorial(N) when N > 0 -> N * factorial(N-1);
factorial(0) -> 1.
anonymous function fun(X, Y) -> X+Y end
piecewise defined anonymous function fun([]) -> null;
  ([X|_]) -> X
execution control
prolog erlang
if if
  X == 0 -> io:format("no hits~n");
  X == 1 -> io:format("one hit~n");
  X > 1 -> io:format("~w hits~n", [X])
try/catch X = 0.
try (7 div X) of
  Val -> Val
  error:badarith -> 0
receive message -module(echo).
loop() ->
    {From, Msg} ->
      From ! { self(), Msg},
    stop ->
spawn process Pid = spawn(echo, loop, []).
send message Pid ! {self(), hello}.
list processes processes().
file handles
prolog erlang
open file for reading open('foo.txt', read, Fd).
open file for writing open('foo.txt', write, Fd).
close file close(Fd).
read line X = io:get_line("type line: ").
read character get_char(X). X = io:get_chars("type char: ", 1).
read term read(X). {ok,X} = io:read("type term: ").
write character put_char("A").
write term X = hello, write(X). io:write(X).
printf format('foo: ~s ~2f ~w~n', ["bar", 3.1415, 7]). io:format("foo: ~s ~.2f ~w~n", ["bar", 3.1415, 7]).
prolog erlang
file test, regular file test filelib:is_file("/etc/hosts")
file size filelib:file_size("/etc/hosts")
prolog erlang
build pathname filename:join("/etc", "passwd")
dirname and basename filename:dirname("/etc/passwd")
absolute pathname filename:absname("..")
glob paths returns list of strings:
make directory filelib:ensure_dir("/tmp/foo/bar/")
directory test filelib:is_dir("/tmp")
processes and environment
prolog erlang
command line arguments binds Argv to list of atoms representing command line args:
current_prolog_flag(argv, Argv).
when invoked by escript the command line arguments are passed to the function main in the invoked file as a list of strings.
program name
exit halt(1). halt(1).
libraries and namespaces
prolog erlang
load file ways to load file
define namespace in file factorial.erl
definition of factorial
compile namespace c(factorial).
use function in namespace factorial:factorial(7).
prolog erlang
inspect namespace factorial:module_info().
help help().
clear variable f(X).
clear all variables f().
display processes i().
_____________________________________________________________________________________ _____________________________________________________________________________________

version used

Version used for testing the examples in the sheet.

show version

How to determine the version.

Grammar and Invocation

hello world

A "Hello, World!" program.


The native compiler.


Sometimes the HiPE native compiler must be installed separately.

Modules can be compiled to native code, but an Erlang runtime is still required to run the code.

bytecode compiler

The bytecode compiler.


The interpreter.


How to associate an interpreter with a file on a Unix system.


How to run the read-evaluate-print loop.

block delimiters

How blocks are delimited. A block is a sequence of statements which are executed in order.

statement terminator

How statements are terminated.

end-of-line comment

The syntax for a comment which goes to the end of the current line.

multiple line comment

The syntax for a delimited comment which can span lines.

Variables and Expressions

Arithmetic and Logic

true and false

The literals for true and false.


Values which evaluate as false in a boolean context.

logical operators

short circuit operators

relational operators


Relational operators can be used on values with different types. In this case the precedence is determined by
the type according to this sequence:

number < atom < reference < fun < port < pid < tuple < list < binary

If a comparison is performed on an integer and a float, the integer will be converted to a float. =:= and =/= do not perform conversions and thus will always return false and true respectively when called on an integer and a float.

arithmetic expression

arithmetic operators

unary negation

integer division

How to find the quotient of two integers.

integer division by zero

The result of dividing an integer by zero.

float division

How to perform float division of two integers.

float division by zero

The result of dividing a float by zero.



sqrt -1

transcendental functions

float truncation

absolute value

random number

random seed

bit operators


string literal

newline in literal

character escapes


Some of the Erlang backslash escapes are not derived from C:

\d delete
\s space





number to string

string to number

atom to string

string to atom



Regular Expressions

Dates and Time



Algebraic Data Types


function definition

function definition with guards


The expressions in guards must be side-effect free. Thus they can only contain the following:

  • bound variables
  • literals
  • type tests: is_atom, is_boolean, is_tuple, …
  • relational operators
  • arithmetic operators
  • boolean operators
  • a few built-in functions

Execution Control

File Handles

read line


io:get_line accepts an argument which is displayed as a prompt. The return value is a string which includes the newline.

read character


io:get_chars accepts two arguments. The first is a string which is displayed as a prompt. The second is the number of characters to be read. The function keeps reading lines until the requested number of characters has been collected. The return value is a string which can contain newlines if a line of less than the requested number of characters was entered.



Processes and Environment

Libraries and Namespaces




SWI Prolog Reference Manual
Prolog: The ISO Standard Document


Erlang Reference Manual User's Guide
Erlang Standard Library

content of this page licensed under creative commons attribution-sharealike 3.0