簡體   English   中英

無法將預期類型`a`與實際類型`Integer`相匹配

[英]Couldn't match expected type `a` with actual type `Integer`

我有一個treeBuild函數沒有得到編譯,因為where子句中的簽名:

unfold :: (a -> Maybe (a,b,a)) -> a -> BinaryTree b
unfold f x = case f x of Nothing -> Leaf
                         Just (s,t,u) -> Node (unfold f s) t (unfold f u)

treeBuild :: Integer -> BinaryTree Integer
treeBuild n = unfold f 0
    where f :: a -> Maybe (a,b,a)
          f x
              | x == n = Nothing
              | otherwise = Just (x+1, x, x+1)        

而且我有以下編譯器錯誤:

* Couldn't match expected type `a' with actual type `Integer'
  `a' is a rigid type variable bound by
    the type signature for:
      f :: forall a b. a -> Maybe (a, b, a)
    at D:\haskell\chapter12\src\Small.hs:85:16
* In the second argument of `(==)', namely `n'
  In the expression: x == n
  In a stmt of a pattern guard for
                 an equation for `f':
    x == n
* Relevant bindings include
    x :: a (bound at D:\haskell\chapter12\src\Small.hs:86:13)
    f :: a -> Maybe (a, b, a)
      (bound at D:\haskell\chapter12\src\Small.hs:86:11)

f簽名有什么問題?

錯誤

在您的程序中,您將編寫:

treeBuild :: Integer -> BinaryTree Integer
treeBuild n = unfold f 0
    where f :: a -> Maybe (a,b,a)
          f x
              | x == n = Nothing
              | otherwise = Just (x+1, x, x+1)

因此,這意味着您要檢查Integera之間的相等性。 但是(==)具有類型簽名: (==) :: Eq a => a -> a -> Bool 因此,這意味着在Haskell中,兩個操作數應具有相同的類型

因此,您有兩個選擇:(1)指定f函數,或者(2)概括treeBuild函數。

專門f功能

treeBuild :: Integer -> BinaryTree Integer
treeBuild n = unfold f 0
    where f :: Integer -> Maybe (Integer,Integer,Integer)
          f x
              | x == n = Nothing
              | otherwise = Just (x+1, x, x+1)

在這里,我們簡單地使f為函數f :: Integer -> Maybe (Integer,Integer,Integer)

泛化treeBuild函數

我們可以-並建議這樣做-泛化treeBuild函數(並稍微泛化f函數):

treeBuild :: (Num a, Eq a) => a -> BinaryTree a
treeBuild n = unfold f 0
    where f x
              | x == n = Nothing
              | otherwise = Just (x+1, x, x+1)

然后f將具有類型f :: (Num a, Eq a) => a -> Maybe ( a,a,a )

從現在開始,我們可以為數字類型的任何類型構建樹並支持相等性。

暫無
暫無

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

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