作家Monad示例 - 从`do`表示法到'>> =`表示法

时间:2014-08-11 01:49:12

标签: haskell monads

Learn You a Haskell介绍了这个作家Monad的例子:

import Control.Monad.Writer  

gcd' :: Int -> Int -> Writer (DiffList String) Int  
gcd' a b  
    | b == 0 = do  
        tell (toDiffList ["Finished with " ++ show a])  
        return a  
    | otherwise = do  
        result <- gcd' b (a `mod` b)  
        tell (toDiffList [show a ++ " mod " ++ show b ++ " = " ++ show (a `mod` b)])  
        return result 

如何使用>>=而非do表示法编写此示例?

1 个答案:

答案 0 :(得分:2)

以下是诀窍:

gcd'' :: Int -> Int -> Writer (DiffList String) Int
gcd'' a b
    | b == 0 = tell (toDiffList ["Finished with " ++ show a]) >> return a
    | otherwise = gcd'' b (a `mod` b) >>= (\result -> tell (toDiffList [show a ++ " mod " ++ show b ++ " = " ++ show (a `mod` b)]) >> return result)