aboutsummaryrefslogtreecommitdiff
path: root/challenge-039/stuart-little/haskell/ch-2.hs
blob: 52e8b24b53e0fd253edb79c4b3d52868d8d1775c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env runghc

-- run <script> <RPN expression with space-separated tokens>

import Data.Maybe (isJust,fromJust,)
import System.Environment (getArgs,)
import Test.Tasty.Options (safeRead,)

rpnEval :: [Float] -> [(String,Float->Float->Float)] -> [String] -> [Float]
rpnEval stack dict input
  |null input =stack
  |isJust nxt =rpnEval ((fromJust nxt):stack) dict (tail input)
  |isJust op =rpnEval (((fromJust op) s f):rest) dict (tail input)
  |otherwise =error "parsing error" where
     nxt = safeRead (head input)::Maybe Float
     op = lookup (head input) dict
     (f:s:rest) = stack

main = do
  input <- getArgs
  let dict = [ ("+",(+))
             , ("-",(-))
             , ("*",(*))
             , ("/",(/))]
  print $ rpnEval [] dict input