Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and add elements in a list in Scheme?

Tags:

list

scheme

I want to define a method that take an integer as input and creates dynamically a list of all descending integer numbers to zero. I find trouble into calling method for the n-1 element

like image 978
topless Avatar asked Jan 19 '26 10:01

topless


2 Answers

It's not all that pretty but this should work, tested in DrScheme.

(define (gen-list x )
  (if (= x 0) (list 0) (cons x (gen-list (- x 1)))))
like image 136
zellio Avatar answered Jan 22 '26 00:01

zellio


Now that it's a homework question, I think a tail-recursive version could be an alternative.

  (define (gen-list x)  
           (let lp ((n 0) (ret '())) 
              (if (> n x) 
              ret 
              (lp (1+ n) (cons n ret)))))
like image 39
NalaGinrut Avatar answered Jan 21 '26 23:01

NalaGinrut



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!