哈斯克尔的堆运动

时间:2016-01-10 11:46:27

标签: haskell

我已经完成了这个练习,我必须从堆中删除最小元素并返回一个元组(a,b),其中a =元素被移除,b =新堆。

那么我的代码在哪里

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是我的第一个真正的编码经验,所以我很抱歉打扰这些简单的问题,但我真的很感激帮助。

1 个答案:

答案 0 :(得分:1)

你走了:

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是你的朋友