Created
February 21, 2017 18:41
-
-
Save dboyliao/68aaad37339e3cf6ebe2eab78dab546c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- http://learnyouahaskell.com/functionally-solving-problems | |
-- Reverse Polish notation calculator | |
import System.IO (hFlush, stdout) | |
import Text.Read (readMaybe) | |
main :: IO() | |
main = do | |
putStr "Enter an expression " | |
hFlush stdout | |
userInput <- getLine | |
case (solveRP userInput :: Maybe Float) of | |
Nothing -> putStrLn "Nothing!" | |
Just answer -> putStrLn (show answer) | |
main | |
solveRP :: (Num a, Read a, Fractional a) => String -> Maybe a | |
solveRP = head . foldl solver [] . words | |
where -- solver :: [Maybe a] -> String -> [Maybe a] -- why comment out this line is an error? | |
solver (Nothing:_) _ = [Nothing] | |
solver (Just x:Just y:ys) "*" = Just (x*y):ys | |
solver (Just x:Just y:ys) "+" = Just (x+y):ys | |
solver (Just x:Just y:ys) "-" = Just (y-x):ys | |
solver (Just x:Just y:ys) "/" = Just (y/x):ys | |
solver xs numStr = (readMaybe numStr):xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment