构建列表Scheme / DrRacket中的构建列表

时间:2013-01-19 07:26:58

标签: list scheme racket

尝试制作一个包含n个元素的列表,每个列表都包含r个元素。即 (function 2 3)将是(list (list 0 0 0)(list 0 1 2))。这些元素是通过将第n个元素乘以从0开始的rth元素来生成的。这是我的代码:

(define (nr nc)     
  (build-list nr (lambda (x) 
                   (build-list nc (lambda (x) (* x 1))))))

所以我(function 2 3)出现在(list (list 0 1 2)(list 0 1 2)),我无法弄清楚如何将第一个列表乘以0,将第二个列表乘以1,将第三个乘以2,依此类推。

2 个答案:

答案 0 :(得分:1)

你很亲密:

(define (build nr nc)     
  (build-list nr (lambda (r) 
                   (build-list nc (lambda (c) (* r c))))))

> (build 2 3)
'((0 0 0) (0 1 2))

> (build 3 3)
'((0 0 0) (0 1 2) (0 2 4))

替代方案:

(define (build2 nr nc)
  (for/list ([r nr])
    (for/list ([c nc])
      (* r c))))

答案 1 :(得分:0)

(define (range n)
  (define (range-iter i accum)
    (if (= i 0) (cons 0 accum)
        (range-iter (- i 1) (cons i accum))))
  (range-iter (- n 1) `()))

(define (nested-list n r)
  (map 
   (lambda (multiplier) 
     (map 
      (lambda (cell) (* cell multiplier)) 
      (range r))) 
   (range n)))