簡體   English   中英

Haskell錯誤“因使用...而沒有(Eq a0)的實例”

[英]Haskell error “No instance for (Eq a0) arising from a use of…”

任何人都知道為什么以下代碼在“ matchListWith eq [] [] ”中失敗?

- failure.hs

matchListWith :: (Eq a) => (a -> a -> Bool) -> [a] -> [a] -> Bool
matchListWith f (x:xs) (y:ys) = (f x y) && (matchListWith f xs ys)
matchListWith _ []     []     = True
matchListWith _ _      _      = False

eq :: (Eq a) => a -> a -> Bool
eq a b = (a == b)

main = do
   print (matchListWith eq [1, 3] [1, 3])
   print (matchListWith eq [1, 3] [1])
   print (matchListWith eq [1] [1, 3])
   print (matchListWith eq [3, 1] [1, 3])
   print (matchListWith eq [1] [])
   print (matchListWith eq [] [])

- eof

錯誤是:

failure.hs:16:11:
    No instance for (Eq a0) arising from a use of `matchListWith'
    The type variable `a0' is ambiguous
    Possible fix: add a type signature that fixes these type variable(s)
    Note: there are several potential instances:
      instance Eq a => Eq (GHC.Real.Ratio a) -- Defined in `GHC.Real'
      instance Eq () -- Defined in `GHC.Classes'
      instance (Eq a, Eq b) => Eq (a, b) -- Defined in `GHC.Classes'
      ...plus 22 others
    In the first argument of `print', namely `(matchListWith eq [] [])'
    In a stmt of a 'do' block: print (matchListWith eq [] [])
    In the expression:
      do { print (matchListWith eq [1, 3] [1, 3]);
           print (matchListWith eq [1, 3] [1]);
           print (matchListWith eq [1] [1, 3]);
           print (matchListWith eq [3, 1] [1, 3]);
           .... }

奇怪的是,如果我在GHCi中加載兩個函數, matchListWith eq [] [] ,就可以了。

*Main> matchListWith eq [] []
True
*Main> 

我正在使用GHC版本7.6.3。

原因是因為你打電話的時候

matchListWith eq [] []

編譯器不知道它是什么類型的列表。 它只知道它是[a]類型的值,但是它沒有對它進行Eq a =>約束。 將其更改為

matchListWith eq [] ([] :: [Int])

它應該編譯


有時你必須給GHC一些幫助,以了解它正在使用的類型。 如果你嘗試的話會是一樣的

myFunc :: m Int
myFunc = do
    let x = 1
        y = 2
    return $ x + y

這不會編譯,因為沒有告訴編譯器mMonad ,你必須添加額外的上下文

myFunc :: Monad m => m Int

它的工作原理。

它在GHCi中工作的原因是因為有更多急切的類型推斷。 GHCi通常會選擇比GHC更具體的類型,以使交互式部件更易於使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM