Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert string every nth element in a list of strings

Tags:

clojure

lisp

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)))))
like image 906
Nick Tchayka Avatar asked Jul 17 '14 01:07

Nick Tchayka


Video Answer


1 Answers

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"
like image 151
TacticalCoder Avatar answered Oct 02 '22 15:10

TacticalCoder