开发者

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

I want to define a method that take an integer as input and creates dynamically a list of all descending integ开发者_高级运维er numbers to zero. I find trouble into calling method for the n-1 element


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


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


If you're using PLT scheme, the comprehensions library will let you do this rather neatly:

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

Just an alternative to the recursive form...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜