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.pl
hello :-
  format('Hello, World!~n'),
  halt.

$ swipl -q -t hello -f ./hello.pl
Hello, World!
$ cat hello.erl
-module(hello).
-export([hello_world/0]).

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

$ 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
repl
 
$ 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
end
case case X of
  1 -> true;
  0 -> false
end
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)).
abs(-3)
abs(-3.2)
integer overflow
float literal with exponent 2.0e2
-2.0E-2
2.0e2
-2.0E-2
random number is(X, random(100)).
??
random:uniform().
random:uniform(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
8#52
16#2A
strings
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).
trim
both sides, left side, right side
string:strip(" lorem ")
string:strip(" lorem", left)
string:strip("lorem ", right)
pad
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).
string:to_upper("lorem")
string:to_lower("LOREM")
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).
length("hello")
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).
[65]
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")
end.
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().
lists
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].
Head
tail [_|X] = [1,2,3]. tl([1,2,3])
or use pattern matching:
[_|Tail] = [1,2,3].
Tail
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]).
tuples
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
record
prolog erlang
functions
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
end
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])
end.
for
try/catch X = 0.
try (7 div X) of
  Val -> Val
catch
  error:badarith -> 0
end.
receive message -module(echo).
-export([loop/0]).
 
loop() ->
  receive
    {From, Msg} ->
      From ! { self(), Msg},
      loop();
    stop ->
      true
  end.
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").
put_char(65)
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]).
files
prolog erlang
file test, regular file test filelib:is_file("/etc/hosts")
filelib:is_regular("/etc/hosts")
file size filelib:file_size("/etc/hosts")
directories
prolog erlang
build pathname filename:join("/etc", "passwd")
dirname and basename filename:dirname("/etc/passwd")
filename:basename("/etc/passwd")
absolute pathname filename:absname("..")
glob paths returns list of strings:
filelib:wildcard("/etc/*")
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 data.pl:
[data].
['data.pl'].
consult(data)
define namespace in file factorial.erl
-module(factorial).
-export([factorial/1]).
definition of factorial
compile namespace c(factorial).
use function in namespace factorial:factorial(7).
reflection
prolog erlang
inspect namespace factorial:module_info().
repl
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.

compiler

The native compiler.

erlang:

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.

interpreter

The interpreter.

shebang

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

repl

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.

falsehoods

Values which evaluate as false in a boolean context.

logical operators

short circuit operators

relational operators

erlang:

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.

power

sqrt

sqrt -1

transcendental functions

float truncation

absolute value

random number

random seed

bit operators

Strings

string literal

newline in literal

character escapes

erlang:

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

\d delete
\s space

concatenate

replicate

trim

pad

number to string

string to number

atom to string

string to atom

split

join

Regular Expressions

Dates and Time

Lists

Tuples

Algebraic Data Types

Functions

function definition

function definition with guards

erlang:

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

erlang:

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

read character

erlang:

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.

Files

Directories

Processes and Environment

Libraries and Namespaces

Reflection

REPL

Prolog

SWI Prolog Reference Manual
Prolog: The ISO Standard Document

Erlang

Erlang Reference Manual User's Guide
Erlang Standard Library

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