繁体   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