Haskell: 无法构造无限类型: a ~ Maybe a

Haskell: Cannot construct the infinite type: a ~ Maybe a

我有以下二叉树的定义和一个获取最左边元素的函数,或者 return Nothing 如果树是空树,但是它说 x (类型a) 是无限类型,因为它 returns 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,但您尝试 return 它作为类型 Maybe a 的值。但是,因为 a 是类型变量,类型检查器会尝试查看是否存在 Maybe 的某些实例使 aMaybe a 统一,从而导致 infinite-type错误。

使用 pure(或 Just)return 正确类型的值。

leftistElement (Node x left _) =
  if left == EmptyTree
    then pure x
    else leftistElement left