fork download
  1. -module(prog).
  2. -export([main/0, eval4th/2, tokenize/1]).
  3.  
  4. tokenize(S) ->
  5. [(fun(T) ->
  6. case string:to_float(T) of
  7. {error, _} ->
  8. case string:to_integer(T) of
  9. {error, _} -> T;
  10. {Int, _} -> Int
  11. end;
  12. {Float, _} -> Float
  13. end
  14. end)(E) || E <- string:tokens(S, " ")].
  15.  
  16. eval4th(Que, []) -> Que;
  17. eval4th(Que, [H|T]) ->
  18. Q = case H of
  19. "+" -> ope2items(Que, fun(A, B) -> A + B end);
  20. "-" -> ope2items(Que, fun(A, B) -> A - B end);
  21. "*" -> ope2items(Que, fun(A, B) -> A * B end);
  22. "/" -> ope2items(Que, fun(A, B) -> A / B end);
  23. "." -> {A, Q0} = pop1item(Que), io:format("~p~n", [A]), Q0;
  24. N when is_number(N) -> queue:in_r(N, Que);
  25. _ -> io:format("*** unexpected token [~p] ***~n", [H]), throw({exit, Que})
  26. end,
  27. eval4th(Q, T).
  28.  
  29. ope2items(Que, Ope) ->
  30. {B, A, Q} = pop2items(Que),
  31. queue:in_r(Ope(A, B), Q).
  32.  
  33. pop2items(Que) ->
  34. case queue:out(Que) of
  35. {{value, B}, Q1} ->
  36. case queue:out(Q1) of
  37. {{value, A}, Q2} -> {B, A, Q2};
  38. {empty, _Q2} -> io:format("** empty second **~n", []), throw({exit, Que})
  39. end;
  40. {empty, _Q1} -> io:format("** empty first **~n", []), throw({exit, Que})
  41. end.
  42.  
  43. pop1item(Que) ->
  44. case queue:out(Que) of
  45. {{value, A}, Q} -> {A, Q};
  46. {empty, _Q} -> io:format("** empty top **~n", []), throw({exit, Que})
  47. end.
  48.  
  49. main() ->
  50. eval4th(queue:new(), tokenize("3 2 1 + * 1 - 4 / .")).
Success #stdin #stdout 0.19s 23408KB
stdin
Standard input is empty
stdout
2.0