简体   繁体   中英

Scheme Descending order

I'm new to scheme, so I apologize for the elementary question ahead of time. I'm trying to create a recursive descending list. Currently it returns (1 2 3) instead of (3 2 1)

I think the problem is, is that I'm placing my new element at the front instead of the end of the list. However, I'm not quite sure how to get it as I keep getting errors when I try.

Here's what I have so far:

(define (descend N mylist)  
  (if (= N 0) mylist
      (descend (- N 1) (cons N mylist))))

(descend 3 '())

First of all, the mylist argument is wholly unnecessary. It's never anything but the empty list, so it can simply be omitted.

Second of all, if you don't need your function to be tail recursive, then simply reorder the structure of your calls to cons and descend so that the list is built in the opposite direction.

(define (descend N)
  (if (= N 0) '()
      (cons N (descend (- N 1)))))

If you need a tail-recursive version, then it would probably make more sense to create an accumulator with a helper loop and simply iterate in reverse.

(define (descend N)
  (let loop ((x 1)
             (acc '()))
    (if (= x N) (cons x acc)
        (loop (+ x 1) (cons x acc)))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM