Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Erlang. Functional programming.

No description
by

Yuriy Senko

on 21 January 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Erlang. Functional programming.

Erlang. Introduction. by Yuriy Senko What is Erlang? Erlang is a general-purpose concurrent, garbage-collected programming language and runtime system. In general Erlang is a functional language, with strict evaluation, single assignment, and dynamic typing.-- Wikipedia

It was named after Danish mathematician and engineer Agner Krarup Erlang. Single assignment? 1> X = 1.
1
2> X.
1
3> X = 2.
** exception error: no match of right hand side value 2
4> X = 1.
1 Why single assignment is good? Quoting Mike Williams, one of the three inventors of Erlang:
Find the right methods—Design by Prototyping.
It is not good enough to have ideas, you must also be able to implement them and know they work.
Make mistakes on a small scale, not in a production project. Confused? "=" does not mean assign it means "compare with pattern". And if compiler sees that the variable is unbound it tries to make the statement "true" and bound the given value to the variable. Such behavior will force you to write a code without side effects. All kinds of side effects is strictly prohibited in functional programming. Assignment in Erlang works just like it works in algebra.
If 2x = 4 then x = 2 and it cannot be equal 1, 4 , 5 or any other value except 2. Эрланг (пинд. Error Language, также Enlarg) — небыдлокодерский язык программирования, придуманный расовой шведской компанией Ericsson (без Sony) с целью захватить мир. Выгодно отличается от Хаскелла тем, что на нём реально можно писать полезные программы (и даже зарабатывать кровавые доллары). Функционален, многопоточен и необычайно полон матана. На нем можно делать динамические опердени, не приседая со штангой! Официально заявлено, что язык назван в честь математика Агнера Краупа Эрланга, но всем понятно, что это аббревиатура от Ericsson Language. Going deeper Data type overview Integers - arbitrary size whole numbers.
Floats - double precision floating point numbers
Atoms - named symbolic constants (must starts from lowercase or be enclosed with single quotes).
Boolean - represented with "true" and "false" atoms.
Lists - a variable length collection of elements of any types enclosed with "[]".
Tuples - compound data type with fixed number of terms. Functions func_name(arg1, arg2, ... ) -> <function body>; %clause 1
....
func_name(arg1, arg2,...) -> <function body>. %clause n Example 1 area({square, X}) -> X * X;
area({rectangle, Width, Ht}) -> Width * Ht;
area({circle, R}) -> 3.14159 * R * R. This function will return an area of square, rectangle, circle. Usage: 1> geometry:area({square, 5}).
25
2> geometry:area({circle, 5}).
78.53975
3> geometry:area({rectangle, 5, 4}).
20 Example 2 for(Max, Max, F) -> [F(Max)];
for(Counter, Max, F) -> [F(Counter) | for(Counter+1, Max, F)]. Implementation of FOR loop: 1> lib_misc:for(1, 10, fun(X) -> X end).
[1,2,3,4,5,6,7,8,9,10]
2> lib_misc:for(1, 10, fun(X) -> X*X end).
[1,4,9,16,25,36,49,64,81,100] Unnamed functions fun(args) -> <body> end. List comprehensions 1> [2*N || N <- [1,2,3,4]].
[2,4,6,8] 2> [X || X <- [1,2,3,4,5,6,7,8,9,10], X rem 2 =:= 0].
[2,4,6,8,10] 3> RestaurantMenu = [{steak, 5.99}, {beer, 3.99}, {poutine, 3.50}, {kitten, 20.99}, {water, 0.00}].
[{steak,5.99},
{beer,3.99},
{poutine,3.5},
{kitten,20.99},
{water,0.0}]
4> [{Item, Price*1.07} || {Item, Price} <- RestaurantMenu, Price >= 3, Price =< 10].
[{steak,6.409300000000001},{beer,4.2693},{poutine,3.745}] pyth(N) -> [{X,Y,Z} || X<-lists:seq(1,N), Y<-lists:seq(1,N), Z<-lists:seq(1,N), X*X+Y*Y=:=Z*Z].

2> pyth:pyth(10).
[{3,4,5},{4,3,5},{6,8,10},{8,6,10}] Let's try something more mind-blowing odds_and_evens(L) -> odds_and_evens(L, [], []).
odds_and_evens([H|T], Odds, Evens) ->
case (H rem 2) of
1 -> odds_and_evens(T, [H|Odds], Evens);
0 -> odds_and_evens(T, Odds, [H|Evens])
end;
odds_and_evens([], Odds, Evens) -> {lists:reverse(Odds), lists:reverse(Evens)}. 1> c(lib_misc).
{ok,lib_misc}
2> lib_misc:odds_and_evens(lists:seq(1,10)).
{[1,3,5,7,9],[2,4,6,8,10]} Split a given list into 2 lists: first
should contain odd numbers, and second should contain even numbers. No fear guards are here! right_age(0) -> false;
right_age(1) -> false;
right_age(2) -> false;
...
right_age(16) -> false;
right_age(17) -> false;
right_age(_) -> true. What if you need to do something like this? Guards will help you. right_age(X) when X >= 18 -> true;
right_age(_) -> false. You can combine as many guards as you want separating theme by "," (andalso), ";" (orelse). You can not use your own functions in guard (because they could has side effects). Boolean algebra. OMG 1. > true and false.
false
2> false or true.
true
3> true xor false.
true
4> not false.
true
5> not (true and true).
false The boolean operators "and" and "or" will always evaluate arguments on both sides of the operator. Boolean algebra. OMG 2. 6> 5 =:= 5.
true
7> 1 =:= 0.
false
8> 1 =/= 0.
true
9> 5 =:= 5.0.
false
10> 5 == 5.0.
true
11> 5 /= 5.0.
false =:= means identical while == means equal (the same with /= and =/=). Boolean algebra. OMG 3. 12> 1 < 2.
true
13> 1 < 1.
false
14> 1 >= 1.
true
15> 1 =< 1.
true You need to keep an eye on "=<" operator, because it's a little bit backward. Boolean algebra. OMG 4. Keep in mind the following thing:
number < atom < reference < fun < port < pid < tuple < list < bit string 13> 5 =:= true.
false
14> 0 == false.
false
15> 1 < false.
true Erlang does not actually has a boolean type. "true" and "false" is a reserved atoms. Boolean algebra. OMG. %% note, this one would be better as a pattern match in function heads!
%% I'm doing it this way for the sake of the example.
help_me(Animal) ->
Talk = if Animal == cat -> "meow";
Animal == beef -> "mooo";
Animal == dog -> "bark";
Animal == tree -> "bark";
true -> "fgdadfgna"
end,
{Animal, "says " ++ Talk ++ "!"}. Everything is Expression Even IF, CASE and TRY...CATCH This is ELSE section. It always matches. IF ELIF Exceptions Errors in Erlang erlang:error() Unexpected run-time error. Should not (and mostly cannot) be handled. Most system runtime errors are of that type. Exit (exit/1 - internal
exit/2 - external) Internal exit terminates a single process, external exit terminates multiple parallel processes. Throw A throw is a class of exceptions used for cases that the programmer can be expected to handle. In comparison with exits and errors, they don't really carry any 'crash that process!' intent behind them, but rather control flow. Parallel nature of Erlang Recursion and Tail Recursion. Recursion. The easy way. Let's write a function to calculate a Nth Fibonacci number: Don't worry! Tail recursion is here to rescue. fib_p(0) -> 0;
fib_p(1) -> 1;
fib_p(N) when N>=2 -> fib_p(N-1) + fib_p(N-2). Do you see a problem here?

Hint: On my computer the calculation of fib_p(35) takes more than 40sec. Recursion. The easy way. Recursion. The easy way. That's how the function calculates fib(4) Tail recursion Fibonacci fib_t(N) -> fib_t(N, 0, 0, 0).
fib_t(End, N, N1, N2) ->
case N of
End -> N1 + N2; % Nth number reached
0 -> fib_t(End, N+1, 0, 0) ;
1 -> fib_t(End, N+1, 1, 0) ;
_ -> fib_t(End, N+1, N2+N1, N1) % Regular case
end. TBD Q andalso A Inspired by... http://learnyousomeerlang.com/ Programming Erlang https://github.com/dyp2000/Russian-Armstrong-Erlang Learn you some Erlang for great good. Who use Erlang? Projects: CouchDB, SimpleDB (Amazon), RabbitMQ, Wings 3D (3D modeller), GitHub, Twitterfall (service to view trends from Twitter), Call Of Duty (server core), Mochiweb (light webserver). Companies Amazon (SimpleDB), Yahoo (Delicious), Facebook (chat service backend), T-Mobile (SMS-service and authentication), Motorola (calls processing), Ericson (used in GPRS and 3G mobile networks worldwide)
Full transcript