3

I'm having this simple piece of code, constructing a list of numbers:

#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))

And the result I get is:

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

But what I want of course is:

(1 2 4 7 8)

Is there any way to do it in scheme? I'm using DrRacket.

2 Answers2

1

Already found the answer:

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

Use (cons an-element a-list) to extend a-list with a new element 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)

This produces the results in reverse order, so

(reverse (pseudofizzbuzz 10))

will give you the elements in the correct order.

soegaard
  • 30,661
  • 4
  • 57
  • 106