Professional Documents
Culture Documents
Overview of Erlang
Functional language Single assignment on variables Dynamic typing Pattern matching: functions, conditionals, assignment Excellent concurrency with message passing High fault tolerance, "Let it crash" Modules can be hot loaded OTP standard library
1> c(stuff). {ok,stuff} 2> stuff:get_name({person, {name, "Leaf"}, {age, 22}}). Leaf
Scanner/parser communication
The scanner is a function that takes string and returns list of tokens. The parser is a function that takes list of tokens (or a function that generates tokens) and returns a parse tree. leex: scanner generator yecc: parser generator They come with OTP, standard distribution.
Scanner/parser communication
For Yecc, the list of tokens is a list of tuples containing token, line, and optionally a value.
scanner:scan("(5 + 2) - 3").
[ {'(', 1}, {number, 1, 5}, {'+', 1}, {number, 1, 2}, {')', 1}, {'-', 1}, {number, 1, 3}, {'$end', 1} ]
yeccparser generator
LALR-1 Parser, based on same algorithm as yacc. Matches against patterns of Erlang atoms, and runs associated action. Action is Erlang code. Evaluate directly, eg. to make a simple calculator, Can build tree nodes. Has access to matched tokens using $ syntax. Has following sections Header Terminals, Nonterminals Grammar rules Erlang code Creates a module that exports: parse/1 parse_and_scan/1
Writing an interpreter
Evaluate tokens by pattern matching on their type. Pass environment as function argument.
Message passing
Very cheap to create processes, no shared data. Pass around PID to keep track of processes. Sent messages are stored in mailbox. Receive block lets a process pattern match on messages.
-module(server). -export([loop/0]). loop() -> receive {print, Msg} -> io:format("~p~n", [Msg]) end, loop().
1> Pid = spawn(server, loop, []). <0.42.0> 2> Pid ! {print, "Hello world!"}.
Conclusion
Error messages aren't good Sometimes The grammar and parser can be verbose. Small learning curve. Documentation is decent but lacking.