[Haskell-beginners] gcd

Daniel Carrera daniel.carrera at theingots.org
Fri May 1 16:28:12 EDT 2009


I'm just another Haskell beginner, but what Steve says makes sense. 
Perhaps something like this:

gcd a b | b == 0    = a
         | b < 0     = gcd (-b) a
         | otherwise = gcd b (a `rem` b)

Daniel.

Steve wrote:
> I had a look at the gcd definition in GHC 6.10.1
> ghc-6.10.1/libraries/base/GHC/Real.lhs
> 
> -- | @'gcd' x y@ is the greatest (positive) integer that divides both
> @x@
> -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
> -- @'gcd' 0 4@ = @4 at .  @'gcd' 0 0@ raises a runtime error.
> gcd             :: (Integral a) => a -> a -> a
> gcd 0 0         =  error "Prelude.gcd: gcd 0 0 is undefined"
> gcd x y         =  gcd' (abs x) (abs y)
>                    where gcd' a 0  =  a
>                          gcd' a b  =  gcd' b (a `rem` b)
> 
> Why is gcd 0 0 undefined?
> 
> http://en.wikipedia.org/wiki/Greatest_common_divisor says:
> "It is useful to define gcd(0, 0) = 0 and lcm(0, 0) = 0 because then the
> natural numbers become a complete distributive lattice with gcd as meet
> and lcm as join operation. This extension of the definition is also
> compatible with the generalization for commutative rings given below."
> 
> An added advantage, for haskell, of defining gcd 0 0 = 0 is that gcd
> would change from being a partial function to a total function.
> 
> Regards,
> Steve
> 
> 
> 
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
> 



More information about the Beginners mailing list