无法将预期类型`a`与实际类型`Integer`匹配

zer*_*ing 1 haskell types

我有一个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)        
Run Code Online (Sandbox Code Playgroud)

我有以下编译器错误:

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

签名有什么问题f

Wil*_*sem 8

错误

在您的程序中,您写道:

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

这意味着你要检查an Integer和an 之间的相等性a.但(==)有类型签名:(==) :: 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)
Run Code Online (Sandbox Code Playgroud)

这里我们简单地创建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)
Run Code Online (Sandbox Code Playgroud)

然后f会有类型.f :: (Num a, Eq a) => a -> Maybe (a,a,a)

从现在开始,我们可以为任何类型的数据类型构建树,并支持相等.