Skip to content

Instantly share code, notes, and snippets.

@matoous
Last active June 4, 2018 09:11
Show Gist options
  • Save matoous/e4a7b32f13032a80fee30936af4a969d to your computer and use it in GitHub Desktop.
Save matoous/e4a7b32f13032a80fee30936af4a969d to your computer and use it in GitHub Desktop.
-- Haskell suffix calculator (Polish notation)
import Data.List
suffixCalc :: (Num a, Read a) => String -> a
-- other option is to write this:
-- suffixCalc x = head $ foldl calcFun [] $ words x
suffixCalc = head . foldl calcFun [] . words
where
calcFun (a:b:bs) "+" = (a + b):bs
calcFun (a:b:bs) "-" = (b - a):bs
calcFun (a:b:bs) "*" = (a * b):bs
calcFun numbers n = read n:numbers
main = do
content <- getContents
sequence $ map (print . show . suffixCalc) (lines content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment