view 5-Erlang/README.txt @ 72:e05701354b6e

Add notes from Day 2
author IBBoard <dev@ibboard.co.uk>
date Fri, 02 Feb 2018 20:59:06 +0000
parents 32f018861e36
children
line wrap: on
line source

Install Erlang with "sudo zypper install erlang"

Erlang has a REPL (erl)

Comments are "%", just to be different

Commands need to end with a full-stop (like Prolog)

Erlang has dynamic typing with coercion: 2 + 2 = 4, 2 + 2.0 = 4.0
 → BUT lists aren't just lists, they're strings when the values are printable ASCII 😮
 → AND numbers aren't coerced to strings

As well as strings there are "atoms" - arbitrarily named symbols. 

Variables start with upper-case.

Variables can't be redefined. Trying results in "exception error: no match of right hand side value <the value>"

Lists use square brackets. Tuples use curly braces.

Tuples are apparently used instead of maps and hashes to associate atoms as keys with values.
 → Values are extracted from tuples using pattern matching
 → BUT this implies matching ordering (which isn't the same as maps)

Example:
    Person = {person, {name, "Agent Smith"}, {profession, "Killing programs"}}.
    % person, name and profession are atoms
    {person, {name, Name}, {profession, Profession}} = Person.
    Name. % prints "Agent Smith"
    Profession. % prints "Killing programs"

The initial atom is an Erlang-ism to make it easier to match all "person" tuples

Erlang can pack and unpack bits using "<<Variable:bit_count[ Variable:bit_count[, …]]>>" and then pattern matching to unpack

Functions are well documented at http://erlang.org/doc/apps/stdlib/index.html

Case statements use patern matching:

Animal = "dog".
case Animal of
    "dog" -> underdog;
    "cat" -> thundercat;
    _ -> something_else
end.

If statements use "guards" (conditions) and implies "elseif". Else requires a guard of "true".

if
    X > 0 -> positive;
    X < 0 -> negative;
    true -> zero
end.

Anonymous functions are defined as "fun(Var[, …]) -> [code] end."

List processing is in the "lists" module - e.g. lists:foreach/2 takes function and list of values and calls function on each value in list.
 → There are also map, filter, all and any functions, etc.
 → Interesting extra functions are lists:takewhile/2 and lists:dropwhile/2, which filter or discard from the start of a list based on the function's return

Erlang has list comprehension - similar to Python's, but with Erlang-y syntax.
 → [Function(Val) || Val <- List].   % Call Function on Val for each Val in List
 → Can also be done without a function and just code - e.g. [X * 2 || X <- [1, 2, 3]].
 → Therefore, map(Func,List) can be defined as [ Func(X) || X <- List ].
 → EXCEPT it isn't that simple - there can be multiple clauses after the double-pipe, which can be generators (X <- List) or filter clauses (X < 3)