packages feed

calculator-0.3.0.0: src/Main.hs

{-# LANGUAGE CPP #-}

module Main where

--------------------------------------------------------------------------------

import           Paths_calculator            (version)

--------------------------------------------------------------------------------

import           Calculator.Color            (Color (..), bold, color)
import           Calculator.Evaluator.Base   (evaluate)
import           Calculator.Prim.Bindings    (Bindings)
import           Calculator.Prim.Definitions (defBinds)
import           Calculator.Prim.Result      (Result (..))

--------------------------------------------------------------------------------

import           Data.Version                (showVersion)
import           System.Console.Haskeline

--------------------------------------------------------------------------------

#ifdef PLOT
import           Control.Monad.IO.Class      (liftIO)
#endif

--------------------------------------------------------------------------------

type Repl a = InputT IO a

--------------------------------------------------------------------------------

repl :: Bindings -> Repl ()
repl b = do
  input <- getInputLine $ color Red True "calc> "
  case input of
    Nothing  -> return ()
    Just inp -> process b inp

padOut :: Bindings -> String -> String -> Repl ()
padOut b s m = do outputStr . unlines . map (s ++) . lines $ m
                  repl b

process :: Bindings -> String -> Repl ()
process b inp = case evaluate b inp of
                  Value c -> padOut b " == " $ show c
                  Text t  -> padOut b " ~~ " t
                  Error e -> padOut b " !! " e
                  NewBindings b' -> repl b'
#ifdef PLOT
                  Action io      -> liftIO io >> repl b
#endif

--------------------------------------------------------------------------------

main :: IO ()
main = do
  putStrLn $ "calculator, version "
               ++ showVersion version
               ++ ". Use :? for help."
  runInputT defaultSettings (repl defBinds)
  putStrLn $ "Please report issues at: " ++
       bold "https://github.com/sumitsahrawat/calculator/issues"

--------------------------------------------------------------------------------