Browse Source

initial commit

Josh Bicking 6 years ago
commit
f9e733499d
2 changed files with 29 additions and 0 deletions
  1. 9 0
      README.md
  2. 20 0
      allArgsAdd.hs

+ 9 - 0
README.md

@@ -0,0 +1,9 @@
+# allArgsAdd
+
+A simple program to add all arguments.
+
+Built to explore & implement folding over Monads.
+
+## Build
+
+`ghc allArgsAdd.hs`

+ 20 - 0
allArgsAdd.hs

@@ -0,0 +1,20 @@
+module Main where
+import System.Environment
+import Text.Read
+
+main :: IO ()
+main = do
+  args <- getArgs
+  case (foldMaybeNum [readMaybe s :: Maybe Double | s <- args]) of
+    (Just n) -> roundMaybe n
+    Nothing -> putStrLn "Those weren't numbers!"
+
+foldMaybeNum :: (Num a, Eq a) => [Maybe a] -> Maybe a
+foldMaybeNum x = foldr (\a b -> (+) <$> a <*> b) (Just 0) x
+
+-- Decide whether to print the double as an int, or a double
+roundMaybe :: Double -> IO ()
+roundMaybe n =
+  if n == fromInteger (round n) then
+    (putStrLn . show) (round n :: Integer)
+  else (putStrLn . show) n