哈斯克尔的堆练习



我有一个练习,其中我必须从Heap中删除最小元素,并返回一个带有(a,b)的元组,其中a=删除的元素,b=新的Heap。

我的代码在哪里

removeMin :: Ord a => Heap a -> (a, Heap a)
removeMin (Node r (Node a b c) (Node x y z)) = (r, newHeap (Node a b c) (Node x y z))
  where
    newHeap Empty Empty = Empty
    newHeap h Empty = h
    newHeap Empty h = h
    newHeap (Node a b c) (Node x y z) = (Node (min a x) (newHeap b c) (newHeap y z))

我得到这个错误代码

No instance for (Show (Heap a0)) arising from a use of ‘print’
In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it

当我尝试做类似的事情时

 removeMin (Node 2 (Node 5 (Node 7 Empty Empty) (Node 9 Empty Empty)) (Node 10 (Node 13 Empty Empty) (Node 15 Empty Empty)))

这可能是一个简单的问题,但我是计算机科学的第一年,Haskell是我第一次真正的编码经验,所以很抱歉遇到这么简单的问题。但我真的很感激你的帮助。

开始:

instance (Show a) => Show (Heap a) where
    show (Empty) = "Empty"
    show (Node x a b) = ("Node ") ++ show x ++ (" (") ++ show a ++ (") ") ++ ("(") ++ show b ++ (")")
removeMin :: Ord a => Heap a -> (a,Heap a)
removeMin (Node a e d) = (a,build e d) where
    build (Node a e d) (Node b e2 d2)
        | (a < b) = (Node a (build e d) (Node b e2 d2))
        | otherwise = (Node b (Node a e d) (build e2 d2))
    build a Empty = a
    build Empty b = b

JBB是您的朋友

最新更新