diff options
author | Alexander Sulfrian <alexander@sulfrian.net> | 2010-10-11 20:16:41 +0200 |
---|---|---|
committer | Alexander Sulfrian <alexander@sulfrian.net> | 2010-10-11 20:16:41 +0200 |
commit | 8c8596c17a3c63347574f63c3f93de2b64669720 (patch) | |
tree | 602d10a45561a92625fbbc8040abc4d7f5f283f4 | |
parent | 8780ceda0c192a0a0c79d716a3064a7cc2406ae5 (diff) | |
download | erlang-8c8596c17a3c63347574f63c3f93de2b64669720.tar.gz erlang-8c8596c17a3c63347574f63c3f93de2b64669720.tar.xz erlang-8c8596c17a3c63347574f63c3f93de2b64669720.zip |
added factor to parse things like x^y^z...
added factor,
added parseNumber to parse an integer from the input string
-rw-r--r-- | calc.erl | 81 |
1 files changed, 52 insertions, 29 deletions
@@ -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}. |