data Bst a = Empty | Node (Bst a) a (Bst a)
lElems :: Ord a => a -> Bst a -> Int
lElems _ Empty = -1
lElems n (Node l m r)
| n == m = n
| n > m = lElems n r
| n < m = lElems n l
Run Code Online (Sandbox Code Playgroud)
在这里,您可以看到类型和程序的定义.如果它在树中,我想返回元素,如果不是,则返回-1.
However, I had this problem
Couldn't match expected type `Int' with actual type `a'
`a' is a rigid type variable bound by
the type signature for lElems :: Ord a => a -> Bst a -> Int
at C:\Users\User\workspace\s\src\Main.hs:3:11
Run Code Online (Sandbox Code Playgroud)
有人可以解释我这里有什么问题吗?
在这种n == m情况下,lElems返回n.从类型签名中,函数被声明为始终返回Int.这意味着n 必须是一个Int,因此,不能是任何一个 Ord a.
尝试转换但这可能会要求你进一步限制n成Int返回之前; a.
而不是返回的-1的情况下,你没有找到你要找的内容,请考虑更改返回类型Maybe a,或者是一个Either值.
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |