Advertisement
Guest User

Untitled

a guest
Mar 4th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 0.85 KB | None | 0 0
  1. open System
  2.  
  3. let rec parseAndCalcCore stack tokens =
  4.     match tokens, stack with
  5.     | [], [single] -> single
  6.     | "+"::rest, h1::h2::tail -> parseAndCalcCore (h2 + h1::tail) rest
  7.     | "-"::rest, h1::h2::tail -> parseAndCalcCore (h2 - h1::tail) rest
  8.     | "/"::rest, h1::h2::tail -> parseAndCalcCore (h2 / h1::tail) rest
  9.     | "*"::rest, h1::h2::tail -> parseAndCalcCore (h2 * h1::tail) rest
  10.     | h::rest, _ -> parseAndCalcCore (((h |> double)::stack)) rest
  11.     | _ -> failwith "The stack does not contains needed elements"
  12. let parseAndCalc (expr : string) =
  13.     expr.Split ' '
  14.     |> Array.toList
  15.     |> parseAndCalcCore []
  16.     |> string
  17. let print = parseAndCalc >> Console.WriteLine
  18.  
  19. [<EntryPoint>]
  20. let main argv =
  21.     print "1 1 +"
  22.     print "2 -3 *"
  23.     print "1 1 + 2 3 * -"
  24.     print "1 3 / 2 *"
  25.     print "10 1 2 + 2 + 5 + +"
  26.     0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement