Only keep numbers in descending order by scheme

你。 提交于 2019-12-20 05:29:46

问题


I want to write a function that just keeps the descending order numbers and gets rid of ascending ones.

For example: (descending '(6 5 3 1 2 8)) should give me (6 5 3 1).

Thanks.


回答1:


A list is the result of consing an object onto a list. Or an empty list.

What is consing? It is a built-in operation.

(define (plain-cons x xs)
  (cond
    ((null? xs) (list x))
    (else (cons x xs))))    ; using the built-in

A descending list is the result of descend-consing an object onto a descending list. Or an empty list.

What is a descend-consing? It is a consing such that the resulting list is also descending:

; (descend-cons 3 '())      -> (list 3)
; (descend-cons 8 '(7 3))   -> (cons 8 '(7 3))
; (descend-cons 5 '(8 7 3)) -> (descend-cons 5 '(7 3))

(define (descend-cons x xs)
  (cond
    ((null? xs) (list x))
    (else
       (let ((a (car xs)))
         (cond
           ((>= x a)      ; { 8 '(7 3)) } -> '(8 7 3)
              .... )
           (else          ; { 5 '(8 7 3)) } -> { 5 '(7 3) }
             (.... x 
                   (cdr xs))))))))

Armed with this, the task is easy. We'll write the function descending which turns a list into a descending list, simply as

; (descending '())           ->  '()
; (descending '(x y z ...))  ->  (descend-cons x (..... '(y z ...)))

(define (descending lst)
  (cond
    ((null? lst) lst)
    (else
      (let ((x (car lst))
            (xs (cdr lst)))
        (...... x
                (...... xs))))))

What is the second argument expected by descend-cons? It must be a descending list.

Can we create a descending list, from the list '(y z ...)? What function, that we have in our arsenal, would do this for us?



来源:https://stackoverflow.com/questions/46673924/only-keep-numbers-in-descending-order-by-scheme

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