Skip to content

Instantly share code, notes, and snippets.

@shigemk2 shigemk2/Gcd.scala
Created Aug 12, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.