Created
September 30, 2008 08:42
-
-
Save cooldaemon/13773 to your computer and use it in GitHub Desktop.
Made a calculator using the yecc and leex.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ /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). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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