12

I am currently learning how to write type classes. I can't seem to write the Ord type class with compile errors of ambiguous occurrence.

module Practice where

class  (Eq a) => Ord a  where
    compare              :: a -> a -> Ordering
    (<), (<=), (>=), (>) :: a -> a -> Bool
    max, min             :: a -> a -> a

    -- Minimal complete definition:
    --      (<=) or compare
    -- Using compare can be more efficient for complex types.
    compare x y
         | x == y    =  EQ
         | x <= y    =  LT
         | otherwise =  GT

    x <= y           =  compare x y /= GT
    x <  y           =  compare x y == LT
    x >= y           =  compare x y /= LT
    x >  y           =  compare x y == GT

    -- note that (min x y, max x y) = (x,y) or (y,x)
    max x y 
         | x <= y    =  y
         | otherwise =  x
    min x y
         | x <= y    =  x
         | otherwise =  y

Errors are

Practice.hs:26:14:
    Ambiguous occurrence `<='
    It could refer to either `Practice.<=', defined at Practice.hs:5:10
                          or `Prelude.<=',
                             imported from `Prelude' at Practice.hs:1:8-15
...

and so on. I think it is clashing with the Prelude defined version.

4

2 回答 2

28

问题是您的函数名称与 Prelude 中的标准名称冲突。

为了解决这个问题,您可以添加一个隐藏冲突名称的显式导入声明:

module Practice where

import Prelude hiding (Ord, compare, (<), (<=), (>=), (>), max, min)

...
于 2013-05-07T23:19:28.863 回答
19

hammar 是对的,这是因为与标准 Prelude 名称发生冲突。hiding但除了Prelude中的名称之外,还有另一种解决方案。

您可以导入 Prelude 合格:

module Practice where

import qualified Prelude as P

...

接下来,您可以访问您和标准版本的功能:max将执行您的版本,P.max并将执行标准 Prelude 的。

还有一种方法可以完全隐藏所有标准 Prelude 函数:GHC 的扩展 NoImplicitPrelude ( http://www.haskell.org/haskellwiki/No_import_of_Prelude )。可以激活写

{-# LANGUAGE NoImplicitPrelude #-}

在文件的开头

于 2013-05-07T23:34:35.973 回答