我对二叉树和获取最左边元素的函数有以下定义,或者如果树是Empty树,则返回Nothing,但它说x
(类型为a
(是无限类型,因为它返回Maybe a
?
感谢任何帮助都将不胜感激:(
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Eq)
leftistElement :: (Ord a) => Tree a -> Maybe a
leftistElement EmptyTree = Nothing
leftistElement (Node x left _) =
if left == EmptyTree
then x
else leftistElement left
types.hs:55:10: error:
• Occurs check: cannot construct the infinite type: a ~ Maybe a
• In the expression: x
In the expression:
if left == EmptyTree then x else leftistElement left
In an equation for ‘leftistElement’:
leftistElement (Node x left _)
= if left == EmptyTree then x else leftistElement left
• Relevant bindings include
left :: Tree a (bound at types.hs:53:24)
x :: a (bound at types.hs:53:22)
leftistElement :: Tree a -> Maybe a (bound at types.hs:52:1)
|
55 | then x
| ^
Failed, no modules loaded.
x
的类型为a
,但您尝试将其作为Maybe a
类型的值返回。由于a
是类型变量,因此类型检查器会尝试查看是否存在使a
和Maybe a
统一的Maybe
实例,从而导致无限类型错误。
使用pure
(或Just
(返回正确类型的值。
leftistElement (Node x left _) =
if left == EmptyTree
then pure x
else leftistElement left