summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xrpn.hs28
1 files changed, 15 insertions, 13 deletions
diff --git a/rpn.hs b/rpn.hs
index dbb0f1f..68c0831 100755
--- a/rpn.hs
+++ b/rpn.hs
@@ -1,4 +1,6 @@
1import Control.Monad (join, sequence) 1#!/usr/bin/env runghc
2
3import Control.Monad (join, sequence, forever)
2import System.Environment (getArgs) 4import System.Environment (getArgs)
3import Data.Maybe (listToMaybe, isJust) 5import Data.Maybe (listToMaybe, isJust)
4import Data.Char (isSpace) 6import Data.Char (isSpace)
@@ -39,25 +41,25 @@ fromSymbol _ = (0, 0)
39 41
40 42
41pPrint :: Show a => Symbol a -> String 43pPrint :: Show a => Symbol a -> String
42pPrint (Number x d) = (show x) ++ " ± " ++ (show d) 44pPrint (Number x d) = (show x) ++ " ± " ++ (show d) ++ " (relative error: " ++ (show $ d / x) ++ ")"
43pPrint s = show s 45pPrint s = show s
44 46
45main :: IO () 47main :: IO ()
46main = do 48main = do
47 hSetBuffering stdin LineBuffering 49 hSetBuffering stdin LineBuffering
48 hSetBuffering stdout NoBuffering 50 hSetBuffering stdout NoBuffering
49 (mode:args) <- getArgs 51 forever $ do
50 let symbols = join . join $ map (map words) . map lines $ args 52 putStr "Formula: "
53 line <- getLine
54 let --symbols = join . join $ map (map words) . map lines $ args
55 symbols = words line
51 unknownSymbols = nub $ filter (not . isKnownSymbol) symbols 56 unknownSymbols = nub $ filter (not . isKnownSymbol) symbols
52 symbolMap <- sequence $ map (sequencePair . (\x -> (x, clarifySymbol x))) unknownSymbols 57 symbolMap <- sequence $ map (sequencePair . (\x -> (x, clarifySymbol x))) unknownSymbols
53 let symbolMap' = M.fromList symbolMap 58 let symbolMap' = M.fromList symbolMap
54 symbols' = map (\x -> if x `elem` (M.keys symbolMap') then symbolMap' M.! x else [x]) symbols 59 symbols' = map (\x -> if x `elem` (M.keys symbolMap') then symbolMap' M.! x else [x]) symbols
55 symbols'' = map interpreteSymbol $ join symbols' 60 symbols'' = map interpreteSymbol $ join symbols'
56 let result = evalExpVec symbols'' 61 let result = evalExpVec symbols''
57 case mode of 62 putStrLn . pPrint $ evalExpVec symbols''
58 "n" -> putStrLn . show . fst $ fromSymbol result
59 "e" -> putStrLn . show . snd $ fromSymbol result
60 _ -> putStrLn $ pPrint result
61 63
62clarifySymbol :: String -> IO [String] 64clarifySymbol :: String -> IO [String]
63clarifySymbol s = do 65clarifySymbol s = do