Created
February 27, 2024 19:53
-
-
Save luishendrix92/aa5a0c44b06da21c227171854850d9d6 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Evaluation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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