在球拍中组合子列表

时间:2018-03-19 00:06:33

标签: list racket

我正在处理球拍中的问题,而且我是解决方案的最佳方式,但是,我的程序正在给我这个:

(list
 (list 'a (list 'red 'circle))
 (list 'a (list 'red 'square))
 (list 'a (list 'green 'circle))
 (list 'a (list 'green 'square))
 (list 'a (list 'blue 'circle))
 (list 'a (list 'blue 'square))
 (list 'b (list 'red 'circle))
 (list 'b (list 'red 'square))
 (list 'b (list 'green 'circle))
 (list 'b (list 'green 'square))
 (list 'b (list 'blue 'circle))
 (list 'b (list 'blue 'square)))

而不是:

(list
 (list 'a 'red 'circle)
 (list 'a 'red 'square)
 (list 'a 'green 'circle)
 (list 'a 'green 'square)
 (list 'a 'blue 'circle)
 (list 'a 'blue 'square)
 (list 'b 'red 'circle)
 (list 'b 'red 'square)
 (list 'b 'green 'circle)
 (list 'b 'green 'square)
 (list 'b 'blue 'circle)
 (list 'b 'blue 'square))

我正在尝试找到一个优雅的解决方案来添加到我当前的程序来更改输出,但是遇到了障碍。我试过搞乱附加功能无济于事。也有可能有多个子列表我必须撤消,例如第一个元素是:

(list 'a (list 'red (list 'circle)))

而不是:

(list 'a 'red 'circle)

1 个答案:

答案 0 :(得分:0)

您可以通过两种方式获得所需的输出:您可以修改程序本身以构建所需的列表,您可以获取程序的结果并将其转换为您的程序期望的输出。由于你的问题中没有关于前者的代码,我会建议后者的解决方案。

Racket中存在内置flatten,可以满足您的需求:

(flatten (list 'a (list 'red 'circle))
=> '(a red circle)
(flatten (list 'a (list 'red (list 'circle)))
=> '(a red circle)

或者,您甚至可以通过执行以下操作来转换列表列表:

(map flatten '((a (red circle))
               (a (red square))
               (a (green circle))
               (a (green square))
               (a (blue circle))
               (a (blue square))
               (b (red circle))
               (b (red square))
               (b (green circle))
               (b (green square))
               (b (blue circle))
               (b (blue square))))