模棱两可的事件

use*_*254 11 haskell typeclass

我目前正在学习如何编写类型类.我似乎无法编写具有模糊发生的编译错误的Ord类型类.

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
Run Code Online (Sandbox Code Playgroud)

错误是

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
...
Run Code Online (Sandbox Code Playgroud)

等等.我认为它与Prelude定义的版本发生了冲突.

ham*_*mar 27

问题是你的函数名称与Prelude中的标准名称冲突.

要解决此问题,您可以添加隐藏冲突名称的显式导入声明:

module Practice where

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

...
Run Code Online (Sandbox Code Playgroud)


小智 17

hammar是对的,这是因为与标准的Prelude名字发生了冲突.但除hidingPrelude的名字外,还有另一种解决方案.

您可以导入Prelude合格:

module Practice where

import qualified Prelude as P

...
Run Code Online (Sandbox Code Playgroud)

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

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

{-# LANGUAGE NoImplicitPrelude #-}
Run Code Online (Sandbox Code Playgroud)

在你的文件的最开始