Advertisement
T-D-K

Untitled

Mar 2nd, 2019
1,358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.32 KB | None | 0 0
  1. open System
  2.  
  3. let doAdd (stack : double list) : double list =
  4.     stack.Tail.Head + stack.Head :: stack.Tail.Tail
  5.  
  6. let doSub (stack : double list) : double list =
  7.     stack.Tail.Head - stack.Head :: stack.Tail.Tail
  8.  
  9. let doDiv (stack : double list) : double list =
  10.     stack.Tail.Head / stack.Head :: stack.Tail.Tail
  11.  
  12. let doMul (stack : double list) : double list =
  13.     stack.Tail.Head * stack.Head :: stack.Tail.Tail
  14.  
  15.  
  16. let rec parseAndCalcCore (tokens : string list) (stack : double list) : double =
  17.     match tokens with
  18.         | [] -> stack.Head
  19.         | h::t -> match h with
  20.             | "+" -> doAdd stack |> parseAndCalcCore t
  21.             | "-" -> doSub stack |> parseAndCalcCore t
  22.             | "/" -> doDiv stack |> parseAndCalcCore t
  23.             | "*" -> doMul stack |> parseAndCalcCore t
  24.             | _ -> ((h |> double) :: stack) |> parseAndCalcCore t
  25.            
  26.  
  27. let parseAndCalc (expr : string) : string =
  28.     let tokens = (expr.Split ' ' |> Array.toList)
  29.     parseAndCalcCore tokens [] |> string
  30.    
  31. [<EntryPoint>]
  32. let main argv =
  33.     Console.WriteLine (parseAndCalc "1 1 +")
  34.     Console.WriteLine (parseAndCalc "2 -3 *")
  35.     Console.WriteLine (parseAndCalc "1 1 + 2 3 * -")
  36.     Console.WriteLine (parseAndCalc "1 3 / 2 *")
  37.     Console.WriteLine (parseAndCalc "10 1 2 + 2 + 5 + +")
  38.     0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement