2
\$\begingroup\$

In getting accustomed to Clojure syntax, I wrote the following stutter function:

(defn doublelist [coll]
 (flatten (map (fn [x] [x x]) coll)))
(defn stutter [s]
 (clojure.string/join
 " " (doublelist (clojure.string/split s #" "))))

This duplicates every word in an input string:

(stutter "how are you?")
"how how are are you? you?"

The doublelist function bugs me. It seems that repeating items in a list should be possible without a call to flatten.

Any thoughts?

asked Oct 2, 2012 at 1:44
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

You may use mapcat to omit flatten:

user> (defn doublelist [coll]
 (mapcat #(repeat 2 %) coll))
#'user/doublelist
user> (doublelist [:a :b :c :d])
(:a :a :b :b :c :c :d :d)
answered Oct 2, 2012 at 6:28
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.