将程序的一部分视为球拍中的数据

Treating a part of program as data in Racket

我必须说我真的不知道如何称呼我要找的东西,所以标题可能不太准确。

我有一个程序可以绘制一些点。 generate-list 函数生成一个包含 n (x,y) 坐标的列表,get-points 生成另一个列表,其中每个 x(来自 (x,y))都可以被 n 整除。
我绝对可以调用 points 多少次我需要,但我试图通过只编写一次 points 函数来减少过程。

#lang racket
(require plot)

(define (generate-list n)
  (if (= n 0)
      empty
      (cons (list (random 0 100) (random 0 100))
            (generate-list (- n 1)))))

(define (get-points lst n)
  (if (empty? lst)
      empty
      (if (= (remainder (caar lst) n) 0)
          (cons (car lst) (get-points (cdr lst) n))
          (get-points (cdr lst) n))))

(plot (list
       (axes 0 0)
       (points (get-points (generate-list 1000) 2)
               #:color 2)
       (points (get-points (generate-list 1000) 3)
               #:color 3)
       (points (get-points (generate-list 1000) 4)
               #:color 4)
       (points (get-points (generate-list 1000) 5)
               #:color 5)))

Bellow 是一个没有产生任何有用信息的示例,但我正在寻找可以以类似方式简化代码的内容。

(plot (list
       (axes 0 0)
       (for ([i (in-range 2 5)])
         (points (get-points (generate-list 1000) i)
                 #:color i))))

当然,任何只编写一次 points 函数的替代方案都会有很大帮助。

尝试 for/list instead of for 那里:

(plot (list
       (axes 0 0)
       (for/list ([i (in-range 2 5)])
         (points (get-points (generate-list 1000) i)
                 #:color i))))

一个for loop throws away the values the body-expression produces on each iteration, while the for/list loop puts them into a list, and returns the list so that all the points are included in the input to plot.

(顺便说一句,这个嵌套列表没问题,因为 plot 允许 renderer-tree 作为输入。)