我是Clojure的新手。
我正在开发一个tic tac toe游戏
我试图制作一个"格式化"电路板,这是一个地图,其中位置为关键字,关键字为:x
:o
和:e
,用于值(:e代表空白)。
我想在关键字名称列表中每3个插入一个换行符。
例如"x" "x" "x" "e" "e" "e" "e" "e" "e"
应该转换为"x" "x" "x" "\n" "e" "e" "e" "\n" "e" "e" "e"
然后我会连接这些字符串,以便我可以打印它。
(defn- newline-every
[n list]
(if (empty? list)
[]
(let [[fst snd] (split-at n list)]
(concat
(conj fst "\n")
(newline-every n snd)))))
答案 0 :(得分:4)
它的Clojure所以肯定有很多方法可以在一行中完成。这是一次尝试:
(flatten (interpose "\n" (partition n list))))
当用户 amalloy 发表评论时,永远不会有借口使用flatten
,所以这里有更好的方法:
(apply concat (interpose ["\n"] (partition n list))))
从给出的字符串序列(包含一个字符)开始,给出:
... > (newline-every 3 ["x" "x" "x" "e" "e" "e" "e" "e" "e"])
("x" "x" "x" "\n" "e" "e" "e" "\n" "e" "e" "e")
然后,您可以将其转换为字符串:
... > (apply str (newline-every 3 ["x" "x" "x" "e" "e" "e" "e" "e" "e"]))
"xxx\neee\neee"