Skip to content

Instantly share code, notes, and snippets.

@gabyfle
Last active March 23, 2021 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabyfle/1545289f7d203d9857b9a8cd8d41da7c to your computer and use it in GitHub Desktop.
Save gabyfle/1545289f7d203d9857b9a8cd8d41da7c to your computer and use it in GitHub Desktop.
Evaluation of postfixed expressions using pattern matching and piles
(* 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