Scheme: merge and sort functions
I'm trying to write a function that merges and then sorts a list, but now I have two different functions; one that merges it and one that sorts it. So I'm trying to write another function, that calls either functions, so it can merge and sort a list at once in that function.
This is what I have:
;; this merges the list
(define (merge l1 l2)
(cond ((null? l1) l2)
((null? l2) l1)
((< (car l1) (car l2)) (cons (car l1) (merge (cdr l1) l2)))
(else (cons (car l2) (merge l1 (cdr l2))))))
;; this sorts the list
(define sort
(lambda (lst)
(if (nu开发者_开发技巧ll? lst)
'()
(insert (car lst)
(sort (cdr lst))))))
(define insert
(lambda (elt sorted-lst)
(if (null? sorted-lst)
(list elt)
(if (<= elt (car sorted-lst))
(cons elt sorted-lst)
(cons (car sorted-lst)
(insert elt (cdr sorted-lst)))))))
You define your merge-sort
like this:
(define (merge-sort l1 l2) (sort (merge l1 l2)))
Example:
> (merge-sort (list 8 3 7 4 9 2) (list 5 1 0 6 4))
(0 1 2 3 4 4 5 6 7 8 9)
Why not use one already written for you :)
精彩评论