Skip to content

Instantly share code, notes, and snippets.

@darkf
Created August 12, 2012 23:37
Show Gist options
  • Select an option

  • Save darkf/3335375 to your computer and use it in GitHub Desktop.

Select an option

Save darkf/3335375 to your computer and use it in GitHub Desktop.
F# RPN calculator
type Atom =
| Num of int
| Op of char
let opToProc = function
| '+' -> (+)
| '*' -> (*)
| _ -> failwith "invalid operation"
let rec evalRPN (expr : Atom list) (stack : int list) =
match expr with
| [] -> stack
| Num a :: rst -> evalRPN rst (a :: stack)
| Op op :: rst ->
let rhs = stack.Head
let lhs = stack.Tail.Head
let result = ((opToProc op) lhs rhs)
evalRPN rst (result :: stack.Tail.Tail)
let main =
let r = evalRPN [Num 3; Num 2; Op '+'; Num 2; Op '*'; Num 2; Op '*'] []
printf "result: %d" (r.Head)
System.Console.ReadKey true |> ignore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment