基础程序无法加载(Haskell)

时间:2012-02-21 07:00:22

标签: haskell

我正在尝试加载以下程序

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

但是我收到了错误

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.

我将功能名称从gcd更改为main,我得到了

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.

我不明白这一点。我在这里使用workshop步骤。

1 个答案:

答案 0 :(得分:12)

第一个错误应该是不言而喻的 - 一个名为gcd的函数已经存在。

第二个也很简单。在Haskell中,main是程序的入口点。由于程序需要某种方式来执行IO,main必须采用IO a形式的类型,通常为IO ()。这意味着您应该将您的gcd功能称为其他功能。 (Haskell中的main函数类似于Java中的main方法。)

通常的做法是将其称为gcd',其发音为“gcd prime”。在这种情况下,命名您的函数gcd'表示它只是gcd的不同实现。