intro to erlang

Post on 31-Dec-2015

15 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

OJ Reeves. Intro to Erlang. Agenda. The Boring Stuff Basic syntax, expressions, funcs , records Atoms, BIFs, data types, bools , equality The not so Boring Stuff Pattern matching, guards, binaries Some Interesting Stuff processes, concurrency A Fun Problem Super Basic Webserver. - PowerPoint PPT Presentation

TRANSCRIPT

INTRO TO ERLANGOJ Reeves

Agenda

The Boring StuffBasic syntax, expressions, funcs, recordsAtoms, BIFs, data types, bools, equality

The not so Boring StuffPattern matching, guards, binaries

Some Interesting Stuffprocesses, concurrency

A Fun Problem Super Basic Webserver

Play Along

Load werl or erl, that’s your REPL. Modules? Create one for mucking

around, foo.erl: -module(foo). %% matches file-compile(export_all).%% your stuff goes here

Compile file in REPL: c(foo).Your code is auto-loaded when compiled.

The Boring Stuff IQ = 10. %% “binding”IQ = 10. %% ok, same value boundIQ = 11. %% runtime error

Name = “OJ”. Response = <<“{\”name\”:\”OJ\”}”>>. Point = {1.0, 3.2}.{X, Y} = Point.Tuples can be of mixed “type” / nested

random() -> 4. %% ode to XKCD L = [“I am”, “a list of”, “strings”].

Lists can be of mixed “type”L2 = [1, 10.4, “fear me!”, my_atom].

More Boring Stuff clean(Text) ->

Funs = [fun rem_bad/1, fun add_punc/1],lists:foldl(fun(X, T) -> X(T) end, Text , Funs).

-record(person, {name, age, state=sober}). get_name(#person{name=Name}) ->

Name. set_name(Person, Name) ->

Person#person{name=Name}. Common return values:

ok vs {error, “Reason”} ok = some_module:do_something().

The Last of the Boring Stuff Status = dead.

anything_like_this, ‘OR THIS’ BIF – “Built in Function”

integer_to_list(), list_to_binary(), atom_to_list(), etc. Data types – don’t really have any! Boolean stuff

and, or, xor, andalso, orelse Equality

=:= =/= (basically == and !=)== /= (when mixed “types” such as 1 == 1.0)<, =<, >=, >, etc (=< is not a typo!)

The Not So Boring Stuff

Pattern matching! div(N, 0) -> infinity; %% cont..div(N, D) -> N /D.

first_item_even([H|T]) ->H rem 2 =:= 0.

get_status(P) ->case P#person.name of

○ “OJ” -> loser; %% continue_ -> legend %% no , or .

end. %% terminated here

More Not So Boring Stuff Pattern matching is binding!

rock, paper, scissors (no lizard/spock)Winner = case {Move1, Move2} of

○ {paper, rock} -> player1;○ {rock, scissors} -> player1;○ {scissors, paper} -> player1;○ {Move, Move} -> draw; %% oooh!○ _ -> player2

end. Guards!

is_decrepit(#person{age=Age}) when Age > 80 -> true;is_decrepit(_Person) -> false.

More Not So Boring Stuff

Binaries are special lists<<“can have string data”>>.<<3, 2, 5, 76>>. %% or int data

Can be pattern matched:A = <<1, 2, 3, 4>>.<<B, C, D, E>> = A.

○ C == 2<<F:4, G:8, H:20>> = A.

○ F = 0, G = 16, H = 131844.

Bit syntax – pull apart binaries!

Last of the Not So Boring Stuff

Pulling an MP3 header apart: valid_header(<<2#11111111111:11, B:2,

C:2, _D:1, _E:4, _F:2, _G:1, _Bits:9>>) ->case {B, C} of

○ {1, _} -> false; %% bad version{_, 0} -> false; %% bad layer_ -> true

end; valid_header(_) -> false. Thanks Joe!

Interlude - Fizzbuzz

For each number from 1 to 100, output:“Fizz” if divisible by 3“Buzz” if divisible by 5“FizzBuzz” if divisible by both 3 and 5The number itself otherwise.

Some Interesting Stuff Processes – very cheap, easy to spin up. Not

“native”.spawn(Fun) -> pid()

○ Spawn Fun/0 in a new processspawn(Node, Fun) -> pid()

○ Spawn Fun/0 on the given nodespawn(Mod, Fun, Args) -> pid()

○ Spawn Mod:Fun(Args) in a new processspawn(Node, Mod, Fun, Args) -> pid()

○ See if you can guess…

Also spawn_link() which links processes together.Eg. Notification of crashing

More Interesting Stuff Send message to a process:Pid ! Message.

Message can be any Erlang term. To receive a message:rec() ->receive

○ pattern1 -> action1()…○ pattern2 -> action2()…

after timeout ->○ timeout_action().

end.Loop via recursive calls.

More Interesting Stuff

Demo of echo(). Parallel map:

spawn() for each “job”Wait for response from each PidCombine resultsShow me teh codez.

A Fun Problem

Create a “ring” of N processes. Send a message around the ring. Each node prints the message and

forwards on to the next process. If the message is quit, terminate the

process. Code!

Super Basic Webserver There is an API (inets), but we’ll do our

own. Listen on a port (8000). When connection received, spawn a

process to continue listening. Use current process to handle request. Support GET

Return 200 & content for valid URI.Return 404 otherwise.

CODE!

The End

That’s it. There is no more. Questions? http://buffered.io/ http://twitter.com/TheColonial

top related