Scheme 如何创建类似(3 3 2 1)的列表

Scheme 如何创建类似(3 3 2 1)的列表,scheme,racket,Scheme,Racket,我正在尝试创建一个类似于(3 3 2 1)的列表。 我的代码: (定义函数 (兰姆达(北纬) (定义L) (λ(n) (如果(

我正在尝试创建一个类似于
(3 3 2 1)
的列表。 我的代码:

(定义函数
(兰姆达(北纬)
(定义L)
(λ(n)
(如果(
我需要添加什么才能得到它?
谢谢

我将它分解为三个功能

(define (repeat e n) (if (= n 0) '() (cons e (repeat e (- n 1)))))
(define (count-down n) (if (= n 0) '() (cons n (count-down (- n 1)))))
(define (f n) (apply append (map (lambda (n) (repeat n n)) (count-down n))))

(f 3); => '(3 3 3 2 2 1)
将其展平为单个函数需要如下内容:

(define (g a b) 
      (if (= a 0) '() 
          (if (= b 0) 
              (g (- a 1) (- a 1)) 
              (cons a (g a (- b 1))))))

(define (f n) (g n n))

(f 3) ;=> '(3 3 3 2 2 1)

这是一个尾部递归版本。它以相反的方式进行迭代

(define (numbers from to)
  (define step (if (< from to) -1 1))
  (define final (+ from step))
  (let loop ((to to) (down to) (acc '()))
    (cond ((= final to) acc)
          ((zero? down)
           (let ((n (+ to step)))
             (loop n n acc)))
          (else
           (loop to (- down 1) (cons to acc))))))

(numbers 3 1)
; ==> (3 3 3 2 2 1)
(定义(从到的数字)
(定义步骤(如果( (3 3 3 2 2 1)

要在标准方案中实现这一点,您可能需要将
define
更改为
let*
,因为可以确定
step
在计算
final
时不可用

我将使用一个简单的递归过程来处理
构建列表

(define (main n)
  (if (= n 0)
      empty
      (append (build-list n (const n)) (main (sub1 n)))))

(main 3) ;; '(3 3 3 2 2 1)
(main 6) ;; '(6 6 6 6 6 6 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1)

这是一个尾部递归版本

(define (main n)
  (let loop ((m n) (k identity))
    (if (= m 0)
        (k empty)
        (loop (sub1 m) (λ (xs) (k (append (build-list m (const m)) xs)))))))

(main 3) ;; '(3 3 3 2 2 1)
(main 6) ;; '(6 6 6 6 6 6 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1)

F
的作用是什么?只是一个提示,当您使用
(define(fname arg))
语法而不是
(define fname(lambda(arg)))时,阅读代码要容易得多。
(define (numbers from to)
  (define step (if (< from to) -1 1))
  (define final (+ from step))
  (let loop ((to to) (down to) (acc '()))
    (cond ((= final to) acc)
          ((zero? down)
           (let ((n (+ to step)))
             (loop n n acc)))
          (else
           (loop to (- down 1) (cons to acc))))))

(numbers 3 1)
; ==> (3 3 3 2 2 1)
(define (main n)
  (if (= n 0)
      empty
      (append (build-list n (const n)) (main (sub1 n)))))

(main 3) ;; '(3 3 3 2 2 1)
(main 6) ;; '(6 6 6 6 6 6 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1)
(define (main n)
  (let loop ((m n) (k identity))
    (if (= m 0)
        (k empty)
        (loop (sub1 m) (λ (xs) (k (append (build-list m (const m)) xs)))))))

(main 3) ;; '(3 3 3 2 2 1)
(main 6) ;; '(6 6 6 6 6 6 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1)