본문 바로가기
Programming/Clojure

4Clojure - #32 Duplicate a Sequence

by NAMP 2014. 5. 12.
4Clojure - #32 Duplicate a Sequence

 
Write a function which duplicates each element of a sequence.



(= (__ [1 2 3]) '(1 1 2 2 3 3))


(= (__ [:a :a :b :b]) '(:a :a :a :a :b :b :b :b))



(= (__ [[1 2] [3 4]]) '([1 2] [1 2] [3 4] [3 4]))



(= (__ [[1 2] [3 4]]) '([1 2] [1 2] [3 4] [3 4]))















;; 32. Duplicate a Sequence
;; Write a function which duplicates each element of a sequence.
mapcat #(vector % %)



mapcat #(list % %)



### mapcat
user>  (mapcat #(list % %) [1 2 3])
(1 1 2 2 3 3)

user> (doc mapcat)
clojure.core/mapcat
([f & colls])
  Returns the result of applying concat to the result of applying map
  to f and colls.  Thus function f should return a collection.

user=> (source mapcat)
(defn mapcat
  "Returns the result of applying concat to the result of applying map
  to f and colls.  Thus function f should return a collection."
  {:added "1.0"}
  [f & colls]
    (apply concat (apply map f colls)))
nil

user=> (map #(list % %) [1 2 3])
  ((1 1) (2 2) (3 3))
  user=> (concat (list '(1 1) '(2 2) '(3 3)))
  ((1 1) (2 2) (3 3))
  user=> (concat [1])
  (1)


Solutions:

1


mapcat #(list % %)
maximental's solution:
1


mapcat #(list % %)

hypirion's solution:
1


#(interleave % %)

chouser's solution:
1


#(interleave % %)

jafingerhut's solution:
1


(fn [s] (mapcat (fn [x] [x x]) s))










댓글