Comparing
version 2 and
version 1 backh1. Erlang Study
Origin: "Getting Started With Erlang":http://erlang.org/doc/doc-5.5.1/doc/getting_started/part_frame.html
h2. 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
h2. 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.
h2. 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
h2. 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}. I have chosen c meaning Centigrade (or Celsius) and f meaning Fahrenheit.