Skip to content

Instantly share code, notes, and snippets.

@pirrmann
Last active January 15, 2016 13:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pirrmann/d5e7c5de2a2d3c0b2965 to your computer and use it in GitHub Desktop.
Save pirrmann/d5e7c5de2a2d3c0b2965 to your computer and use it in GitHub Desktop.
Reverse Polish Notation
let (|Operator|_|) s =
match s with
| "+" -> Some (+)
| "-" -> Some (-)
| "*" -> Some (*)
| "/" -> Some (/)
| _ -> None
let eval state input =
match input, state with
| Operator o, o2 :: o1 :: tail -> o o1 o2 :: tail
| _ -> int input :: state
let compute (s:string) =
s.Split([|' '|]) |> Seq.fold eval []
compute "1"
compute "1 2 +"
compute "5 4 - 1 -"
compute "5 4 1 - -"
compute "5 1 2 + 4 * + 3 -"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment