[英]Haskell: Cannot construct the infinite type: a ~ Maybe a
I have the following definition of a binary tree and a function that fetches the leftmost element, or return Nothing if the tree is an Empty tree, however it is saying x
(with type a
) is an infinite type because it returns Maybe a
?我有以下二叉树的定义和一个获取最左边元素的 function,如果树是空树,则返回 Nothing,但是它说x
(类型a
)是无限类型,因为它返回Maybe a
?
Thanks any help would be appreciated:)感谢任何帮助将不胜感激:)
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
has type a
, but you try to return it as a value of type Maybe a
. x
具有a
类型,但您尝试将其作为Maybe a
类型的值返回。 Because a
is type variable, though, the type checker attempts to see if there is some instance of Maybe
that makes a
and Maybe a
unify, which leads to the infinite-type error.但是,因为a
是类型变量,所以类型检查器会尝试查看是否存在使a
和Maybe a
统一的Maybe
实例,这会导致无限类型错误。
Use pure
(or Just
) to return a value of the correct type.使用pure
(或Just
)返回正确类型的值。
leftistElement (Node x left _) =
if left == EmptyTree
then pure x
else leftistElement left
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.