Skip to content

Instantly share code, notes, and snippets.

@wrist
Created June 17, 2015 12:16
Show Gist options
  • Save wrist/5cf042dfe00844b0089a to your computer and use it in GitHub Desktop.
Save wrist/5cf042dfe00844b0089a to your computer and use it in GitHub Desktop.
chapter14_problem1
-- Writerを返す2引数関数を用いたfoldMによる整数の畳込みを行うために、9より大きい数が表れた場合は9より小さい数が表れた場合とは異なるログを残すような関数を実装せよ
import Control.Monad.Writer
binSmallsWriter :: Int -> Int -> Writer [String] Int
binSmallsWriter acc x
| x > 9 = do
tell [show x ++ " too big, not added"]
return acc
| otherwise = do
tell [show x ++ " is added"]
return (acc + x)
{-
GHCi> mapM_ putStrLn $ snd $ runWriter $ foldM binSmallsWriter
0 [2,8,3,1]
2 is added
8 is added
3 is added
1 is added
GHCi> mapM_ putStrLn $ snd $ runWriter $ foldM binSmallsWriter
0 [2,11,3,1]
2 is added
11 too big, not added
3 is added
1 is added
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment