erlangstudy
Erlang Study
Origin: Getting Started With Erlang
The Erlang Shell
You have to tell it you are done entering code by finishing the line with a full stop ”.” and a carriage return
Modules and Functions
In general module and the file name need to be the same. So inside tut.erl write:
-module(tut1).
-export([fac/1]).
fac(1) ->
1;
fac(N) ->
N * fac(N - 1).
The two parts of the fac function are called its clauses.
We end the first part with a ”;” which indicates that there is more of this function to come. the second part ends with a ”.” saying that there are no more parts of this function.
Atoms
Atoms start with a small letter (manual), for example: charles, centimeter, inch. Atoms are simply names, nothing else. They are not like variables which can have a value.
-module(tut2).
-export([convert/2]).
convert(M, inch) ->
M / 2.54;
convert(N, centimeter) ->
N * 2.54.
9> c(tut2).
{ok,tut2}
10> tut2:convert(3, inch).
1.18110
11> tut2:convert(7, centimeter).
17.7800
Tuples
Erlang has a way to group things together to make things more understandable. We call these tuples. Tuples are surrounded by “{” and “}”.
-module(tut3).
-export([convert_length/1]).
convert_length({centimeter, X}) ->
{inch, X / 2.54};
convert_length({inch, Y}) ->
{centimeter, Y * 2.54}.
14> c(tut3).
{ok,tut3}
15> tut3:convert_length({inch, 5}).
{centimeter,12.7000}
16> tut3:convert_length(tut3:convert_length({inch, 5})).
{inch,5.00000}
We have shown tuples with two parts above, but tuples can have as many parts as we want and contain any valid Erlang term.
Tuples have a fixed number of things in them. We call each thing in a tuple an element. So in the tuple {moscow,{c,-10}}, element 1 is moscow and element 2 is {c,-10}.
Lists
Lists in Erlang are surrounded by “[” and “]”. A very useful way of looking at parts of lists, is by using ”|”.18> [First |TheRest] = [1,2,3,4,5]. [1,2,3,4,5] 19> First. 1 20> TheRest. [2,3,4,5]
Note: Variables starting with CAPITAL LETTER. Variable can only be given a value once in its context (scope).
In general we can say we use tuples where we would use “records” or “structs” in other languages and we use lists when we want to represent things which have varying sizes, (i.e. where we would use linked lists in other languages).
Erlang does not have a string date type, instead strings can be represented by lists of ASCII characters.31> [97,98,99]. "abc"