0

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

(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,依此类推。

4

2 回答 2

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))))
于 2013-01-19T09:07:05.390 回答
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)))
于 2013-01-19T08:09:26.013 回答