Skip to content

Instantly share code, notes, and snippets.

@cooldaemon
Created September 30, 2008 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cooldaemon/13773 to your computer and use it in GitHub Desktop.
Save cooldaemon/13773 to your computer and use it in GitHub Desktop.
Made a calculator using the yecc and leex.
$ /path/to/reia/bin/leex calc_scan.xrl
$ /path/to/reia/bin/yecc calc_parse.yrl
$ erlc calc_scan.erl
$ erlc calc_parse.erl
$ erlc calc_eval.erl
$ erl
1> {ok, Scan, _Line} = calc_scan:string("(1 + 2) * 3 - 4").
2> {ok, Exp} = calc_parse:parse(Scan).
3> calc_eval:eval(Exp).
-module(calc_eval).
-author('cooldaemon@gmail.com').
-export([eval/1]).
eval({{'+', _}, Expr1, Expr2}) ->
eval(Expr1) + eval(Expr2);
eval({{'-', _}, Expr1, Expr2}) ->
eval(Expr1) - eval(Expr2);
eval({{'*', _}, Expr1, Expr2}) ->
eval(Expr1) * eval(Expr2);
eval({{'/', _}, Expr1, Expr2}) ->
eval(Expr1) / eval(Expr2);
eval({integer, _, Expr}) ->
Expr.
Nonterminals
expression term block.
Terminals
integer
'(' ')' '+' '-' '*' '/'.
Rootsymbol expression.
expression -> term : '$1'.
expression -> expression '+' term : {'$2', '$1', '$3'}.
expression -> expression '-' term : {'$2', '$1', '$3'}.
term -> block : '$1'.
term -> term '*' block : {'$2', '$1', '$3'}.
term -> term '/' block : {'$2', '$1', '$3'}.
block -> '(' expression ')' : '$2'.
block -> integer : '$1'.
Definitions.
Dig = [0-9]
Rules.
({Dig}{Dig}*) : {token, {integer, TokenLine, list_to_integer(TokenChars)}}.
\+ : {token, {'+', TokenLine}}.
\- : {token, {'-', TokenLine}}.
\* : {token, {'*', TokenLine}}.
\/ : {token, {'/', TokenLine}}.
\( : {token, {'(', TokenLine}}.
\) : {token, {')', TokenLine}}.
(.|\n) : skip_token.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment