Skip to main content

Hi, I'm Mariano Guerra, below is my blog, if you want to learn more about me and what I do check a summary here: marianoguerra.github.io or find me on twitter @warianoguerra or Mastodon @marianoguerra@hachyderm.io

calculadora en erlang parte 2 (agregando floats)

este cambio es muy simple asi que va a ser un post muy corto, voy a resaltar los cambios

en calc_lexer.xrl

Definitions.

D = [0-9]
AOP = (\+|-)
WS = ([\000-\s]|#.*)

Rules.

{AOP} : {token,{add_operator,TokenLine,list_to_atom(TokenChars)}}.
{D}+ : {token,{integer,TokenLine,list_to_integer(TokenChars)}}.
{D}+\.{D}+ : {token,{float,TokenLine,list_to_float(TokenChars)}}.
{WS}+ : skip_token.

Erlang code.

en calc_parser.yrl

Nonterminals
predicate.

Terminals
add_operator integer float.

Rootsymbol predicate.

Left 300 add_operator.

predicate -> predicate add_operator predicate : {unwrap('$2'), '$1', '$3'}.

predicate -> integer : unwrap('$1').
predicate -> float : unwrap('$1').

Erlang code.

unwrap({_,_,V}) -> V.

en calc.erl

-module(calc).
-export([solve/1]).

solve(String) ->
{ok, Tokens, _Endline} = calc_lexer:string(String),
{ok, Tree} = calc_parser:parse(Tokens),
matches(Tree).

matches(A) when is_number(A) -> A;
matches({'+', A, B}) -> matches(A) + matches(B);
matches({'-', A, B}) -> matches(A) - matches(B);
matches(_) -> error.

para facilitar la construccion, les dejo el codigo que tengo en build_calc.erl



-module(build_calc).
-export([build/0, test/0]).

build() ->
leex:file(calc_lexer),
yecc:file(calc_parser),
compile:file(calc_lexer),
compile:file(calc_parser),
compile:file(calc),
ok.