I. Basics of Erlang A. overview ------------------------------------------ ERLANG OVERVIEW Erlang designed for: - reliable distributed systems (telephony) Language Design: - mix of functional and logic programming influences - actor model for concurrency and distribution ------------------------------------------ Why this kind of design? B. data types 1. primitive types ------------------------------------------ PRIMITIVE TYPES IN ERLANG any() number integer() 3, 7 float() 3.14159, 2.7e-3 atom() stop, go port() pid() reference() ------------------------------------------ a. atoms ------------------------------------------ ATOMS symbols with a fast equality test start with a lower case letter an_atom go yes or are enclosed in single quotes: 'Truth' 'Justice' 'american way' Note: Variables identifiers must start with an Upper Case letter or an underscore (_) ------------------------------------------ 2. compound types ------------------------------------------ COMPOUND TYPES IN ERLANG any() binary() <<1:1,0:1>> fun() fun (X) -> X end, fun foo/1 tuple() {point,3,4} T1 | T2 "union types" Synonyms: char() is a small integer() [T] = [] | [T|[T]] string() = [char()] "can be written so" ------------------------------------------ C. means of combination 1. pattern matching ------------------------------------------ PATTERN MATCHING The = operator, unifies both sides: {point,X,Y} = {point,3,4} makes X be 3 and Y be 4. Pattern matching in function clauses : xcoord({point,X,_}) -> X. ycoord({point,_,Y}) -> Y. P = {point,3,4} xcoord(P) returns 3 Case expressions: xcoord(P) -> case P of {point,X,_} -> X end. ------------------------------------------ ------------------------------------------ DIFFERENCES FROM HASKELL PATTERN MATCHES Multiple uses of the same variable: case P of {point,X,X} -> same; _ -> different end can be thought of as sugar for: case P of {point,X,Z} when X =:= Z -> same; _ -> different end Variables that are already determined stand for their value: X = 2, case P of {point,X,_} -> "x coordinate was 2"; {point,Q,_} -> "x coordinate was " ++ integer_to_list(Q) end can be thought of as sugar for: X = 2, case P of {point,Z,_} when Z =:= X -> "x coordinate was 2"; {point,Q,_} -> "x coordinate was " ++ integer_to_list(Q) end ------------------------------------------ 2. functions a. full recursion ------------------------------------------ FULLY RECURSIVE CODE mylength([]) -> 0; mylength([_|T]) -> 1+ mylength(T). ------------------------------------------ b. tail recursion ------------------------------------------ TAIL RECURSION len(Ls) -> len(Ls,0). len([],N) -> N; len([_|T],N) -> len(T,N+1). ------------------------------------------ 3. programs