hc/app/Main.hs

46 lines
1.8 KiB
Haskell
Raw Normal View History

module Main (main) where
2024-09-16 21:29:06 +02:00
import Lib (exprparser, evaluate, replaceVars, Expr, extractVariableDefinitions, updateVariables, parseFullString)
2024-09-15 17:58:53 +02:00
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Ratio
2024-09-15 16:47:34 +02:00
import System.IO
2024-09-16 12:34:30 +02:00
initVars :: Map String Rational
initVars = Map.fromList [("pi", 245850922 % 78256779), ("e", 271801 % 99990)]
main :: IO ()
2024-09-16 12:34:30 +02:00
main = ioLoop initVars
2024-09-15 16:47:34 +02:00
2024-09-15 17:58:53 +02:00
precision = 5 :: Int
showRatio :: Int -> Rational -> String
2024-09-16 10:54:43 +02:00
showRatio p r = (if (r < 0) then "-" else "") ++ prepoint_digits ++ (if (length postpoint_digits > 0) then ("." ++ postpoint_digits) else "")
2024-09-15 17:58:53 +02:00
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)
2024-09-16 12:34:30 +02:00
useResult :: Map String Rational -> Expr -> String
useResult vs expr = either id ((showRatio precision) . evaluate) $ replaceVars expr vs
2024-09-16 12:34:30 +02:00
ioLoop :: Map String Rational -> IO ()
ioLoop vs = do done <- isEOF
if done
then putStrLn "Quit!"
else do inp <- getLine
2024-09-16 21:29:06 +02:00
let expr_res = parseFullString inp
case expr_res of
Left err -> do
putStrLn . show $ err
ioLoop vs
Right expr -> do
let vardefs = extractVariableDefinitions expr
let uvs_res = updateVariables vardefs vs
case uvs_res of
Left err -> putStrLn err
Right uvs -> putStrLn $ useResult uvs expr
ioLoop (either (const vs) (id) uvs_res)
2024-09-15 16:47:34 +02:00