Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Erlang in 5 Minutes

Erlang in 5 Minutes

Lightning talk first given at Ancient City Ruby in April 2013.

Avatar for Anthony Eden

Anthony Eden

April 05, 2013
Tweet

More Decks by Anthony Eden

Other Decks in Programming

Transcript

  1. -module(example1). -export([sum/2]). sum(A, B) -> A + B. $ erl

    Erlang R15B (erts-5.9) Eshell V5.9 (abort with ^G) 1> c(example1). {ok,example1} 2>example1:sum(10, 20). 30 Friday, April 5, 13
  2. 1> X = 10. 10 2> X = 20. **

    exception error: no match of right hand side value 20 3> 10 = X. 10 Friday, April 5, 13
  3. -module(example2). -export([sum/1]). sum(Values) -> sum(Values, 0). sum([], Total) -> Total;

    sum([Value|Rest], Total) -> sum(Rest, Total + Value). 1> c(example2). {ok,example2} 2> example2:sum([10, 20, 30, 40, 50, 100]). 250 Friday, April 5, 13
  4. -module(example3). -export([babble/1]). count(N) -> timer:sleep(10), io:format("The number is ~p~n", [N]).

    babble(NumberOfTimes) -> [spawn(fun() -> count(N) end) || N <- lists:seq(1, NumberOfTimes)]. 1> c(example3). {ok,example3} 2> example3:babble(100). [<0.38.0>,<0.39.0>,<0.40.0>,<0.41.0>,<0.42.0>,<0.43.0>, <0.44.0>,<0.45.0>,<0.46.0>,<0.47.0>,<0.48.0>,<0.49.0>, <0.62.0>,<0.63.0>,<0.64.0>,<0.65.0>,<0.66.0>|...] The number is 4 The number is 3 The number is 2 The number is 1 The number is 56 The number is 61 The number is 55 Friday, April 5, 13
  5. 1> c(example4). {ok,example4} 2> Adder = spawn(example4, adder, []). <0.38.0>

    3> Adder ! {self(), add, 10, 30}. {<0.31.0>,add,10,30} 4> flush(). Shell got 40 ok -module(example4). -export([adder/0]). adder() -> receive {From, add, A, B} -> From ! sum(A, B); {From, _} -> From ! error end. sum(A, B) -> A + B. Friday, April 5, 13
  6. -module(example5). -behavior(gen_server). % Gen server hooks -export([init/1, handle_call/3, handle_cast/2]). -export([handle_info/2,

    terminate/2, code_change/3]). -record(state, {}). % Gen server callbacks init([]) -> {ok, #state{}}. handle_call(Message, From, State) -> io:format("Received call from ~p: ~p~n", [From, Message]), {reply, "Thanks for playing", State}. handle_cast(Message, State) -> timer:sleep(10), io:format("Received cast: ~p~n", [Message]), {noreply, State}. handle_info(_Message, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_PreviousVersion, State, _Extra) -> {ok, State}. Friday, April 5, 13
  7. 1> c(example5). {ok,example5} 2> gen_server:start_link({local, example5}, example5, [], []). {ok,<0.38.0>}

    3> gen_server:call(example5, "Hello, there"). Received call from {<0.31.0>,#Ref<0.0.0.77>}: "Hello, there" "Thanks for playing" 4> gen_server:cast(example5, {foo, 5}). ok Received cast: {foo,5} Friday, April 5, 13