我有以下二叉樹的定義和一個獲取最左邊元素的函式,或者如果樹是空樹則回傳 Nothing,但是它說x(with type 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.
uj5u.com熱心網友回復:
x有 type a,但您嘗試將其作為 type 的值回傳Maybe a。但是,因為a是型別變數,所以型別檢查器會嘗試查看是否有一些這樣的實體Maybemake aand Maybe aunify,這會導致無限型別錯誤。
使用pure(或Just)回傳正確型別的值。
leftistElement (Node x left _) =
if left == EmptyTree
then pure x
else leftistElement left
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434052.html
標籤:哈斯克尔
下一篇:如何定義型別安全的約束玫瑰樹
