Scheme Inserting Pairs into Heap

2019-08-27 07:24发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-08-27 08:06

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.

查看更多
登录 后发表回答