How to run this haskell program in WinGHCi?

Take this for example: http://www.haskell.org/haskellwiki/99_questions/Solutions/32

(**) Determine the greatest common divisor of two positive integer numbers. Use Euclid algorithm.

gcd' 0 y = y
gcd' x y = gcd' (y `mod` x) x
myGCD x y | x < 0     = myGCD (-x) y
          | y < 0     = myGCD x (-y)
          | y < x     = gcd' y x
          | otherwise = gcd' x y
The Prelude includes a gcd function, so we have to choose another name for ours. The function gcd' is a straightforward implementation of Euler algorithm, and myGCD is just a wrapper that makes sure the arguments are positive and in increasing order.

A more concise implementation is:

myGCD :: Integer -> Integer -> Integer
myGCD a b
      | b == 0     = abs a
      | otherwise  = myGCD b (a `mod` b)

How to check it in WinGHCi? What are the steps / workflow for running haskell programs?

Thank!

+5
source share
1 answer
  • Save the code in a file .hssomewhere, for example C:\Haskell\MyGCD.hs.

  • Launch WinGHCi and go to the directory where you saved it with :cd, then load it with :load:

    Prelude> :cd C:\Haskell
    Prelude> :load MyGCD.hs
    [1 of 1] Compiling Main             ( MyGCD.hs, interpreted )
    Ok, modules loaded: Main.
    
  • Now you can play using the function:

    *Main> myGCD 12 10
    2
    

Enter :helpfor more information or see Chapter 2: Using GHCi in the GHC User Guide .

+11
source

All Articles