Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make a lat using cons in scheme?

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.

like image 301
user7273921 Avatar asked Dec 13 '25 14:12

user7273921


2 Answers

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.

like image 74
soegaard Avatar answered Dec 15 '25 11:12

soegaard


Already found the answer:

 (define (flatten x)
    (cond ((null? x) '())
          ((not (pair? x)) (list x))
          (else (append (flatten (car x))
                        (flatten (cdr x))))))
like image 44
user7273921 Avatar answered Dec 15 '25 11:12

user7273921



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!