I'm new to Clojure.
I'm developing a tic tac toe game
I'm trying to make a function that "formats" the board, which is a map with the number of the position as key and the keywords :x
:o
and :e
for values (:e stands for empty).
I want to insert a newline character every 3 in the list of the name of the keywords.
For example "x" "x" "x" "e" "e" "e" "e" "e" "e"
should be converted to "x" "x" "x" "\n" "e" "e" "e" "\n" "e" "e" "e"
then I would concatenate those strings so I can print it.
(defn- newline-every
[n list]
(if (empty? list)
[]
(let [[fst snd] (split-at n list)]
(concat
(conj fst "\n")
(newline-every n snd)))))
It's Clojure so there are surely many ways to do this in one line. Here's one attempt:
(flatten (interpose "\n" (partition n list))))
As user amalloy commented, there's never an excuse to use flatten
, so here's a better way:
(apply concat (interpose ["\n"] (partition n list))))
Which gives, starting from the sequence of strings (which all contain one character) you gave:
... > (newline-every 3 ["x" "x" "x" "e" "e" "e" "e" "e" "e"])
("x" "x" "x" "\n" "e" "e" "e" "\n" "e" "e" "e")
You can then transform that into a string:
... > (apply str (newline-every 3 ["x" "x" "x" "e" "e" "e" "e" "e" "e"]))
"xxx\neee\neee"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With