![](/img/trans.png)
[英]Haskell Couldn't match expected type `Integer' with actual type `[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)
因此,這意味着您要檢查Integer
和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)
在這里,我們簡單地使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.