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

I want to define a method that takes an integer as input and dynamically creates a list of all descending integers to zero. I find a problem with calling a method for element n-1

+3
source share
3 answers

It is not all so beautiful, but it should work, tested in DrScheme.

(define (gen-list x )
  (if (= x 0) (list 0) (cons x (gen-list (- x 1)))))
+5
source

Now, when it comes to homework, I think the alternative could be a recursive version of the tail.

  (define (gen-list x)  
           (let lp ((n 0) (ret '())) 
              (if (> n x) 
              ret 
              (lp (1+ n) (cons n ret)))))
+3
source

If you use the PLT scheme, the concept library will allow you to do this quite accurately:

; natural -> (listof natural)
(define (list-to-zero start-num)
 (for/list ([i (in-range start-num 0 -1)])
  i))

Just an alternative to a recursive form ...

0
source

Source: https://habr.com/ru/post/1736912/


All Articles