erlang noob note

Random notes from reading Programming Erlang:

Syntax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
% primitives

1234.
3.14.

{char,
{class, hunter},
{race, tauron}
}.

[{mining, 95}, {cooking, 80}].

[$S,117,114,112,114,105,115,101]. % "Surprise"

{X, abc} = {123,abc}. % X = 123

REPL

1
2
3
4
5
6
7
% clear all bindings

f().

% quit

q().

Module

1
2
3
-module(test).
-export([sum/1]).
-import(lists, [map/2, sum/1]).

Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
% in test.erl

sum(L) -> sum(L, 0).

sum([], N) -> N;
sum([H|T], N) -> sum(T, H+N).

% usage in repl

c(test).
test:sum([1,2,3]).

% lambda

Double = fun(X) -> 2*X end.
lists:map(Double, [1,2,3,4]).

% list comprehensions

[2*X || X <- [1,2,3,4]].

% guards

f(X,Y) when is_integer(X), X > Y, Y < 6 -> ...

% strict
f(X) when (X == 0) or (1/X > 2) ->

% lazy
g(X) when (X == 0) orelse (1/X > 2) ->

% otherwise
true ->

Record

1
2
3
4
5
-record(task, {desc, work=io}).

Task = #task{desc=clean, work="clean project"}.

Task#task.desc.

Control

case Expression of 
  Pattern1 [when Guard1] -> Expr_seq1;
  Pattern2 [when Guard2] -> Expr_seq2; 
  ...
end

if
  Guard1 -> Expr_seq1;
  Guard2 -> Expr_seq2;
  ...
end

try FuncOrExpressionSequence of 
  Pattern1 [when Guard1] -> Expressions1;
  Pattern2 [when Guard2] -> Expressions2;
  ...
catch
  ExceptionType: ExPattern1 [when ExGuard1] -> ExExpressions1;
  ExceptionType: ExPattern2 [when ExGuard2] -> ExExpressions2;
  ...
after
  AfterExpressions
end

Concurrency / Message box

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
% ping.erl

-module(ping).
-export([loop/0]).

loop() ->
receive
_ ->
io:format("pong~n"),
loop()
end.

% erl

c(ping).
Pid = spawn(fun ping:loop/0).
Pid ! ping. % -> pong

Then I read about OTP, it's pretty awesome.

Then I read

If a calls b in a loop and we recompile b, then a will automatically call the new version of b the next time b is called.

This is just insane ><