Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Stack-based RPN evaluator:
let eval_rpn tokens =
let stack = Stack.create () in
List.iter (fun tok ->
if tok is operator then
let b = Stack.pop stack in
let a = Stack.pop stack in
Stack.push (apply tok a b) stack
else
Stack.push (int_of_string tok) stack
) tokens;
Stack.pop stack
For tokens [3 4 + 2 * 5 -]:
3 4 + -> 7
7 2 * -> 14
14 5 - -> 9
Exercises Stack.create / push / pop, mixed branch on string
equality, multi-arm if/else if for operator dispatch, int_of_string
for token parsing.
39 baseline programs total.
21 lines
531 B
OCaml
21 lines
531 B
OCaml
let eval_rpn tokens =
|
|
let stack = Stack.create () in
|
|
List.iter (fun tok ->
|
|
if tok = "+" || tok = "-" || tok = "*" || tok = "/" then begin
|
|
let b = Stack.pop stack in
|
|
let a = Stack.pop stack in
|
|
let r = if tok = "+" then a + b
|
|
else if tok = "-" then a - b
|
|
else if tok = "*" then a * b
|
|
else a / b
|
|
in
|
|
Stack.push r stack
|
|
end else
|
|
Stack.push (int_of_string tok) stack
|
|
) tokens;
|
|
Stack.pop stack
|
|
|
|
;;
|
|
|
|
eval_rpn ["3"; "4"; "+"; "2"; "*"; "5"; "-"]
|