variables
This commit is contained in:
parent
9e7ad28c5c
commit
3dc3e3b842
2 changed files with 54 additions and 37 deletions
35
app/Main.hs
35
app/Main.hs
|
@ -2,7 +2,7 @@ module Main (main) where
|
|||
|
||||
import Text.Parsec
|
||||
|
||||
import Lib (exprparser, evaluate, replaceVars, Expr)
|
||||
import Lib (exprparser, evaluate, replaceVars, Expr, extractVariableDefinitions)
|
||||
|
||||
import Data.Map (Map)
|
||||
import qualified Data.Map as Map
|
||||
|
@ -10,8 +10,11 @@ import Data.Ratio
|
|||
|
||||
import System.IO
|
||||
|
||||
initVars :: Map String Rational
|
||||
initVars = Map.fromList [("pi", 245850922 % 78256779), ("e", 271801 % 99990)]
|
||||
|
||||
main :: IO ()
|
||||
main = ioLoop
|
||||
main = ioLoop initVars
|
||||
|
||||
precision = 5 :: Int
|
||||
|
||||
|
@ -19,21 +22,19 @@ showRatio :: Int -> Rational -> String
|
|||
showRatio p r = (if (r < 0) then "-" else "") ++ prepoint_digits ++ (if (length postpoint_digits > 0) then ("." ++ postpoint_digits) else "")
|
||||
where
|
||||
prepoint_digits = init . show . round . abs $ (r * 10)
|
||||
postpoint_digits = reverse .dropWhile (=='0') . reverse .(take p) . (drop (length prepoint_digits)) . show . round . abs $ (r * 10^p)
|
||||
postpoint_digits = reverse . dropWhile (=='0') . reverse .(take p) . (drop (length prepoint_digits)) . show . round . abs $ (r * 10^p)
|
||||
|
||||
useResult :: Either ParseError Expr -> String
|
||||
useResult (Right expr) = either id ((showRatio precision) . evaluate) $ replaceVars expr vars
|
||||
useResult (Left error) = show error
|
||||
useResult :: Map String Rational -> Either ParseError Expr -> String
|
||||
useResult vs (Right expr) = either id ((showRatio precision) . evaluate) $ replaceVars expr vs
|
||||
useResult vs (Left error) = show error
|
||||
|
||||
vars :: Map String Rational
|
||||
vars = Map.fromList [("pi", 245850922 % 78256779), ("e", 271801 % 99990)]
|
||||
|
||||
ioLoop :: IO ()
|
||||
ioLoop = do done <- isEOF
|
||||
if done
|
||||
then putStrLn "Quit!"
|
||||
else do inp <- getLine
|
||||
let expr = parse exprparser "<stdin>" inp
|
||||
putStrLn . useResult $ expr
|
||||
ioLoop
|
||||
ioLoop :: Map String Rational -> IO ()
|
||||
ioLoop vs = do done <- isEOF
|
||||
if done
|
||||
then putStrLn "Quit!"
|
||||
else do inp <- getLine
|
||||
let expr = parse exprparser "<stdin>" inp
|
||||
let uvs = either (const vs) (\e -> Map.unionWith (flip const) vs (extractVariableDefinitions e)) expr
|
||||
putStrLn $ useResult uvs expr
|
||||
ioLoop uvs
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue