Created
August 12, 2012 23:37
-
-
Save darkf/3335375 to your computer and use it in GitHub Desktop.
F# RPN calculator
This file contains hidden or 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
| 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