Last active
March 23, 2021 11:47
-
-
Save gabyfle/1545289f7d203d9857b9a8cd8d41da7c to your computer and use it in GitHub Desktop.
Evaluation of postfixed expressions using pattern matching and piles
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
(* Evaluate postfixed expressions *) | |
type 'a status = | |
Number of 'a | |
|Operator of ('a -> 'a -> 'a) | |
|Function of ('a -> 'a) | |
let eval exp = | |
let s = Stack.create () in | |
let n = Array.length exp in | |
for i = 0 to n - 1 do | |
match exp.(i) with | |
| Number(n) -> Stack.push n s | |
| Operator(op) -> Stack.push (op (Stack.pop s) (Stack.pop s)) s | |
| Function(f) -> Stack.push (f (Stack.pop s)) s | |
done; | |
Stack.pop s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment