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.
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.
Already found the answer:
(define (flatten x)
(cond ((null? x) '())
((not (pair? x)) (list x))
(else (append (flatten (car x))
(flatten (cdr x))))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With