hsilop/hsilop.hs

59 lines
1.5 KiB
Haskell
Raw Normal View History

2015-02-26 19:50:12 +01:00
{-# LANGUAGE ViewPatterns #-}
import Data.List
2015-02-26 23:12:56 +01:00
import Text.Read
2015-02-27 00:58:54 +01:00
import Text.Printf
2015-02-26 23:12:56 +01:00
import Control.Monad
2015-02-26 19:50:12 +01:00
main :: IO ()
2015-02-27 00:58:54 +01:00
main = io (result . rpn)
2015-02-26 19:50:12 +01:00
2015-02-27 00:58:54 +01:00
-- Interact line-by-line
2015-02-26 19:50:12 +01:00
io :: (String -> String) -> IO ()
2015-02-26 23:51:05 +01:00
io f = interact (unlines . map f . filter (not . null) . lines)
2015-02-26 19:50:12 +01:00
2015-02-27 00:58:54 +01:00
-- Pretty print RPN result/errors
result :: Either String Double -> String
result (Left err) = "Ꞥ∘ " ++ err
result (Right x) = printf ("ꟼ∘ " ++ format) x where
2015-02-27 01:10:10 +01:00
format = if ceiling x == floor x then "%.0f" else "%.10f"
2015-02-27 00:58:54 +01:00
-- Solve a RPN expression
2015-02-26 23:12:56 +01:00
rpn :: String -> Either String Double
2015-02-27 00:58:54 +01:00
rpn = foldM parse [] . words >=> return . head where
parse (y:x:xs) (flip lookup dyad -> Just f) = Right (f x y : xs)
parse (x:xs) (flip lookup monad -> Just f) = Right (f x : xs)
parse xs (flip lookup nilad -> Just k) = Right (k : xs)
parse xs x = case readMaybe x of
Just x -> Right (x : xs)
Nothing -> Left "syntax error"
2015-02-26 19:50:12 +01:00
-- dyadic functions
dyad = [ ("+", (+))
, ("-", (-))
, ("*", (*))
, ("/", (/))
, ("^", (**)) ]
-- monadic functions
monad = [ ("sin" , sin )
, ("asin" , asin)
, ("cos" , cos )
, ("acos" , acos)
, ("tan" , tan )
, ("atan" , atan)
, ("ln" , log )
, ("sqrt" , sqrt)
, ("sgn" , signum)
, ("abs" , abs)
, ("floor", fromIntegral . floor)
, ("ceil" , fromIntegral . ceiling) ]
-- niladic functions
nilad = [ ("pi" , pi)
, ("e" , exp 1)
, ("phi", (1 + sqrt 5)/2) ]