Skip to content

Instantly share code, notes, and snippets.

@luishendrix92
Created February 27, 2024 19:53
Show Gist options
  • Save luishendrix92/aa5a0c44b06da21c227171854850d9d6 to your computer and use it in GitHub Desktop.
Save luishendrix92/aa5a0c44b06da21c227171854850d9d6 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Evaluation
exception RPN_eval
type token =
| Num of float
| Binary of (float -> float -> float)
| Unary of (float -> float)
let eval_rpn tokens =
let rec aux ~stack tokens =
match tokens, stack with
| [], [ result ] -> result
| Num x :: tokens, stack -> aux ~stack:(x :: stack) tokens
| Binary f :: tokens, b :: a :: stack -> aux ~stack:(f a b :: stack) tokens
| Unary f :: tokens, a :: stack -> aux ~stack:(f a :: stack) tokens
| _ -> raise RPN_eval
in
aux ~stack:[] tokens
;;
let () =
print_float
(eval_rpn
[ Num 4.0
; Num 5.0
; Num 10.0
; Binary ( /. )
; Binary ( +. )
; Unary Float.floor
]);
print_newline ()
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment