Scheme Inserting Pairs into Heap

孤人 提交于 2020-01-06 05:51:57

问题


This is part of a homework assignment that I can't seem to figure out. I was wondering if someone could point me in the right direction?

The problem reads:

(insert-list-of-pairs vw-pair-list heap) evaluates to the heap resulting from inserting all of the value-weight pairs from the list vw-pair-list into the heap heap.

The following functions were created earlier in the homework for use in this problem:

(define (create-heap vw-pair left right)
    (list vw-pair left right))

(define (h-min heap)
    (car heap))

(define (left heap)
    (cadr heap))

(define (right heap)
    (caddr heap))

In the previous problem I was able to successfully add a pair to the heap using this code:

(define (insert vw-pair heap)
    (if (null? heap)
        (create-heap vw-pair '() '())
        (if (< (weight vw-pair) (weight (h-min heap)))
            (create-heap vw-pair (right heap) (insert (h-min heap) (left heap)))
            (create-heap (h-min heap) (right heap) (insert vw-pair (left heap))))))

I tried to implement a similar procedure using the following code without success:

(define (insert-list-of-pairs vw-pair-list heap)
    (if (null? vw-pair-list)
        heap
        (if (< (car vw-pair-list) (h-min heap))
            (create-heap (car vw-pair-list) (right heap) 
                          (insert-list-of-pairs (cdr vw-pair-list) heap))
            (create-heap (h-min heap) (right heap) 
                          (insert-list-of-pairs vw-pair-list heap)))))

Any and all help would be greatly appreciated!


回答1:


There are good reasons that your previous problem was defining insert.
Not only do you now know how to implement insert, but you also have a function that you can use for insertion so you never need to implement it again.

Because what is a list of such pairs?

If it's not empty, it's one pair followed by a list of pairs.
And you already have a function that inserts one pair into a heap.

If only you had a function that inserts a list of pairs into a heap, you could use that to insert the rest of your list into your heap, then insert your list's first element into that heap, and then you would be done.

But - Eureka! - the "insert a list of pairs into a heap" function is the one you're writing.
So, you recurse:

(define (insert-list-of-pairs vw-pair-list heap)
    (if (null? vw-pair-list)
        heap
        (insert (car vw-pair-list)
                (insert-list-of-pairs (cdr vw-pair-list) heap))))

and then you're done.



来源:https://stackoverflow.com/questions/47046147/scheme-inserting-pairs-into-heap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!