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
表示法编写此示例?
答案 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)