2

I am trying to load the following program

gcd a b = if b == 0
         then a
      else gcd b (rem a b)

But I get the error

Prelude> :l euclidean.hs 
[1 of 1] Compiling Main             ( euclidean.hs, interpreted )

euclidean.hs:3:8:
    Ambiguous occurrence `gcd'
    It could refer to either `Main.gcd', defined at euclidean.hs:1:0
                          or `Prelude.gcd', imported from Prelude
Failed, modules loaded: none.

I changed the function name from gcd to main and I get

Couldn't match expected type `IO t'
           against inferred type `a -> a -> a'
    In the expression: main
    When checking the type of the function `main'
Failed, modules loaded: none.

I dont understand this. I am using the workshop step here.

yayu
  • 7,758
  • 17
  • 54
  • 86
  • 5
    Don't use tabs as indentation. – Matvey Aksenov Feb 21 '12 at 07:25
  • @MatveyB.Aksenov Is there any specific reason why? – yayu Feb 21 '12 at 18:31
  • Tabs in Haskell are defined to be 8 spaces. This may not be the way your (or your collaborators) editor displays them which would lead to confusing errors. See http://stackoverflow.com/questions/1269888/invisible-identation-error-in-haskell-caused-load-fail-in-ghci or http://stackoverflow.com/questions/1694097/haskell-compiler-error-not-in-scope or dozens similar posts here. – Matvey Aksenov Feb 21 '12 at 23:22

1 Answers1

12

The first error should be self-evident--a function called gcd already exists.

The second one is also simple. In Haskell, main is the entry point of the program. Since the program needs some way to do IO, main has to have a type in the form IO a, usually IO (). What this means is you should call your gcd function something else. (The main function in Haskell is akin to the main method in Java.)

The usual practice is to call it gcd', which is pronounced "gcd prime". In this case, naming your function gcd' signifies that it is just a different implementation of gcd.

Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214