简体   繁体   English

Haskell中的堆运动

[英]Heap exercise in Haskell

I've got this exercise where I've got to remove the minimum element from a Heap and return a tuple with (a,b) where a = the element removed and b = the new Heap. 我已经完成了本练习,其中必须从堆中删除最小的元素,然后返回带有(a,b)的元组,其中a =删除的元素,b =新的堆。

So where's my code 那我的代码在哪里

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))

And I get this error code 我得到这个错误代码

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

when I try to do something like this 当我尝试做这样的事情

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

This might be an easy problem, but I'm in my first year of Computer Science and Haskell is my first real coding experience so I'm sorry to bother with such simples questions, but I really appreciate the help. 这可能是一个简单的问题,但是我进入计算机科学专业的第一年,而Haskell是我第一次真正的编码经验,因此很抱歉打扰这些简单的问题,但是我非常感谢您的帮助。

Here you go: 干得好:

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 is your friend JBB是你的朋友

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM