Skip to content

Instantly share code, notes, and snippets.

@zsol
Last active December 12, 2015 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zsol/4741625 to your computer and use it in GitHub Desktop.
Save zsol/4741625 to your computer and use it in GitHub Desktop.
Sums its arguments and also prints them in order
#!/usr/bin/env runghc
import System.Environment
import Control.Monad.Writer
import Control.Applicative
mySum :: (Num a, Show a) => [a] -> Writer [String] a
mySum [] = return 0
mySum (x:xs) = censor ((show x):) ((x+) <$> mySum xs)
main = do
args <- getArgs
let (sum, logs) = runWriter $ mySum $ map read args
print logs
print $ "Sum: " ++ show sum
#!/usr/bin/env runghc
import System.Environment
import Control.Monad.Writer
import Control.Applicative
import System.Time
type WriterIO a = WriterT [String] IO a
mySum :: (Num a, Show a) => [a] -> WriterIO a
mySum [] = return 0
mySum (x:xs) = do
logLine <- liftIO $ myLog x
censor (logLine:) ((x+) <$> mySum xs)
where
myLog :: (Num a, Show a) => a -> IO String
myLog num = do
time <- getClockTime
return $ (show time) ++ " " ++ show num
main = do
args <- getArgs
(sum, logs) <- runWriterT $ mySum $ map read args
print logs
print $ "Sum: " ++ show sum
@zsol
Copy link
Author

zsol commented Feb 8, 2013

$ ./tmp 1 2 3
["1","2","3"]
"Sum: 6"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment