Skip to content

Instantly share code, notes, and snippets.

@shigemk2
Created August 12, 2015 06:15
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 shigemk2/89bd79e982f7a478a8d7 to your computer and use it in GitHub Desktop.
Save shigemk2/89bd79e982f7a478a8d7 to your computer and use it in GitHub Desktop.
import scalaz._
import Scalaz._
object Gcd {
def main(args: Array[String]): Unit = {
def gcd(a: Int, b: Int): Writer[List[String], Int] =
if (b == 0) for {
_ <- List("Finished with " + a.shows).tell
} yield a
else
List(a.shows + " mod " + b.shows + " = " + (a % b).shows).tell >>= { _ => gcd(b, a % b) }
println(gcd(8, 3).run)
}
}
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)
main = do
print $ fst $ runWriter (gcd' 8 3)
mapM_ putStrLn $ snd $ runWriter (gcd' 8 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment