方案:合并和排序功能
我正在尝试编写一个对列表进行合并然后排序的函数,但现在我有两个不同的函数;一种将其合并,一种将其排序。所以我试图编写另一个函数,它调用任一函数,以便它可以在该函数中立即合并和排序列表。
这就是我所拥有的:
;; 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)))))))
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)))))))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像这样定义您的
merge-sort
:示例:
You define your
merge-sort
like this:Example:
为什么不使用已经为您编写的:)
Why not use one already written for you :)