Escolar Documentos
Profissional Documentos
Cultura Documentos
Conditional evaluation
!
factorial(X,K) ->
case X of
0 -> K(1);
X -> factorial(X-1,(fun (X1) -> K(X * X1) end))
end.
if
Guard1 -> expression11, expression12, .. ;
Guard2 -> expression21, expression22, .. ;
... ;
Guardn -> expressionn1, expressionn2, ..
end
Examples
Which of the following examples show a good practice
in the use of if construct
mayor(X) ->
if
X > 0 -> mayorAcero;
X < 0 -> menorACero;
true -> igualACero
end.
if
X rem 2 == 1 -> odd;
X rem 2 == 0 -> even
end
case X rem 2 of
1 -> odd;
0 -> even
end
Only use:
!
!
!
!
!
!
bounded variables
literals (constant values)
predicates to test value types
terms comparison like ==, =/=, <, >, etc.
arithmetic expressions
boolean expressions (using and, or, not, xor, etc., operators)
Examples of guards
Some BIFs
BIF
Description
hd/1
tl/1
length/1
tuple_size/1
element/2
setelement/3
append_element/2
Functions
Description
atom_to_list/1, list_to_atom/1,
list_to_existing_atom/1
list_to_tuple/1, tuple_to_list/1
float/1, list_to_float/1
float_to_list/1, integer_to_list/1
Conversion examples
1> atom_to_list(monday).
"monday"
2> list_to_existing_atom("tuesday").
** exception error: bad argument
in function list_to_existing_atom/1
called as list_to_existing_atom("tuesday")
3> list_to_existing_atom("monday").
monday
4> list_to_tuple(tuple_to_list({one,two,three})).
{one,two,three}
5> float(1).
1.00000
6> round(10.5).
11
7> trunc(10.5).
10
Function
Description
Build a dictionary
Returns a new dictionary appending a new keyvalue pair (or replacing the key-value pair, if it
exists)
Meta-programming
The ability of a function to decide what other functions
must be called in runtime is known as meta-programming
! Programs that create other programs and then execute
them
! The apply/3 function (module, function, arguments (a list))
allows us to evaluate a function inside a module with the
arguments established
!
Function
Description
date/0
time/0
now/0
Exercises (1)
!
Normal recursion
Tail recursion
CPS recursion
foldr version
Exercises (2)
!
!
!