From 8c8596c17a3c63347574f63c3f93de2b64669720 Mon Sep 17 00:00:00 2001 From: Alexander Sulfrian Date: Mon, 11 Oct 2010 20:16:41 +0200 Subject: added factor to parse things like x^y^z... added factor, added parseNumber to parse an integer from the input string --- calc.erl | 81 +++++++++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 52 insertions(+), 29 deletions(-) diff --git a/calc.erl b/calc.erl index 4bf5967..a24b915 100644 --- a/calc.erl +++ b/calc.erl @@ -1,30 +1,53 @@ -module(calc). --export([eval/1]). - -eval(Formular) -> - eval(Formular,[]). - -eval([C | Formular], T) when integer(C) -> - eval(Formular, parseDigit(T, C)); - -eval([C | Formular], T) when C == "." -> - eval(Formular, parseDigit(T, C)); - -eval([C | Formular], T) when C == "+" -> - eval(Formular, [{plus, C}] ++ T); -eval([C |Formular], T) when C == "-" -> - eval(Formular, [{minus, C}] ++ T); -eval([C |Formular], T) when C == "*" -> - eval(Formular, [{mal, C}] ++ T); -eval([C |Formular], T) when C == "/" -> - eval(Formular, [{durch, C}] ++ T); - -eval([], P) -> - P. - -parseDigit([{digit, Last} | Tail], Current) when list(Last) -> - [{digit, Last ++ Current} | Tail]; -parseDigit([{digit, Last} | Tail], Current) -> - [{digit, [Last] ++ Current} | Tail]; -parseDigit(Tail, Current) -> - [{digit, Current} | Tail]. +-export([factor/1]). + +factor(Input) -> + {Tail, Number2} = parseNumber(Input, []), + {_, Result} = factorExtended(Tail, Number2), + Result. + +factor(Input, Number1) when is_integer(Number1) or is_float(Number1) -> + {Tail, Number2} = parseNumber(Input, []), + Result = math:pow(Number1, Number2), + factorExtended(Tail, Result); + +factor([], Number) -> + {[], Number}. + +factorExtended([$^|Tail], Result) -> + factor(Tail, Result); +factorExtended(Tail, Result) -> + {Tail, Result}. + + +parseNumber([$ |Input], []) -> + %% skip spaces at start + parseNumber(Input, []); +parseNumber([$-|Input], []) -> + parseNumber(Input, "-"); +parseNumber([Current|Input], Number) when ($0 =< Current) and ($9 >= Current) -> + parseNumber(Input, Number ++ [Current]); +parseNumber(Input, Number) -> + {Input, list_to_integer(Number)}. + +%% eval(Formular) -> +%% term(Formular,[]). + +%% term([" "|Input], Parsed) -> +%% term(Input, Parsed); +%% term([Current|Formular], Parsed) -> +%% {ParsedFirst, Number1} = parseNumber([Current|Formular], []). + +%% parseOperator([$ |Input]) -> +%% parseOperator(Input); +%% parseOperator([Operator|Input]) -> +%% {ok, list_to_atom(Operator)}; +%% parseOperator([]) -> +%% {error, unexpected_end_of_input}. + +%% sum(Number1, Number2, '+') -> +%% {ok, Number1 + Number2}; +%% sum(Number1, Number2, '-') -> +%% {ok, Number1 - Number2}; +%% sum(_, _, _) -> +%% {error, invalid_operator}. -- cgit v1.2.3