Haskell
すごいH本
第14章14.1
import Control.Monad.Writer
gcd' :: Int -> Int -> Writer [String] Int
gcd' a b
| b == 0 = do
tell ["Finished with " ++ show a]
return a
| otherwise = do
tell [show a ++ " mod " ++ show b ++ " = " ++ show (a `mod`b)]
gcd' b (a `mod` b)
Prelude> :l 14.1
[1 of 1] Compiling Main ( 14.1.hs, interpreted )
Ok, modules loaded: Main.
*Main> fst $ runWriter (gcd' 8 3)
Loading package transformers-0.3.0.0 ... linking ... done.
Loading package mtl-2.1.2 ... linking ... done.
1
*Main> mapM_ putStrLn $ snd $ runWriter (gcd' 8 3)
8 mod 3 = 2
3 mod 2 = 1
2 mod 1 = 0
Finished with 1
第14章14.5
import Control.Monad
powerset :: [a]->[[a]]
powerset xs = filterM (\x->[True,False]) xs
Prelude> :l 14.5
[1 of 1] Compiling Main ( 14.5.hs, interpreted )
Ok, modules loaded: Main.
*Main> powerset [1,2,3]
[[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]
0 件のコメント:
コメントを投稿
注: コメントを投稿できるのは、このブログのメンバーだけです。