[英]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 (null? 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: 您可以像这样定义merge-sort
:
(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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.