有没有办法在计划中使用cons?

时间:2016-12-09 17:44:27

标签: scheme racket nested-lists

我正在使用这段简单的代码,构建一个数字列表:

#lang scheme

(define pseudofizzbuzz (lambda (x)
             (cond
               ((zero? x) (quote ()))
               ((or (integer? (/ x 3)) (integer? (/ x 5))) (cons (quote ()) (pseudofizzbuzz (- x 1))))
               (else (cons x (pseudofizzbuzz (- x 1)))))))

(define reverselist (lambda (lat)
                  (cond
                    ((null? lat) (quote ()))
                    (else
                     (cons (reverselist (cdr lat)) (list (car lat))))))) 


(reverselist (pseudofizzbuzz 10))

我得到的结果是:

 ((((((((((() 1) 2) ()) 4) ()) ()) 7) 8) ()) ())

但我当然想要的是:

(1 2 4 7 8)

有没有办法在计划中做到这一点?我正在使用DrRacket。

2 个答案:

答案 0 :(得分:1)

已经找到了答案:

 (define (flatten x)
    (cond ((null? x) '())
          ((not (pair? x)) (list x))
          (else (append (flatten (car x))
                        (flatten (cdr x))))))

答案 1 :(得分:1)

使用(cons an-element a-list)扩展a-list新元素an-element

#lang racket

(define pseudofizzbuzz
  (lambda (x)
    (cond
      ((zero? x)
       (quote ()))
      ((or (integer? (/ x 3)) (integer? (/ x 5)))
       (pseudofizzbuzz (- x 1)))
      (else
       (cons x (pseudofizzbuzz (- x 1)))))))

(define reverselist
  (lambda (lat)
    (cond
      ((null? lat) 
       (quote ()))
      (else        
       (cons (reverselist (cdr lat)) (list (car lat))))))) 

(pseudofizzbuzz 10)

这会以相反的顺序生成结果,所以

(reverse (pseudofizzbuzz 10))

将以正确的顺序为您提供元素。