Clojure Programming/Examples/API Examples/Sequences
interpose
edituser=> (apply str (interpose "|" ["hi" "mum" "and" "dad"]))
"hi|mum|and|dad"
interleave
edituser=> (interleave [1 2 3] [:a :b :c])
(1 :a 2 :b 3 :c)
reverse
edituser=> (reverse [1 2 3])
(3 2 1)
user=> (apply str (interpose " " (reverse (.split "I am cold" " "))))
"cold am I"
butlast
edituser=> (butlast "hello")
(\h \e \l \l)
next
edituser=> (next [1 2 3 4 5])
(2 3 4 5)
nfirst
edituser=> (nfirst [[1 2 3] [4 5 6] [7 8 9]])
(2 3)
nnext
edituser=> (nnext [1 2 3 4 5])
(3 4 5)
second
edituser=> (second [:a \b "c"])
\b
nth
edituser=> (nth [1 2 3 4 5] 3)
4
replace
edituser=> (replace {\l ""} "hello world")
(\h \e "" "" \o \space \w \o \r "" \d)
user=> (apply str (replace {\l ""} "hello world"))
"heo word"
Sequence Building
editconj
edituser=> (conj [1 2 3] 4)
[1 2 3 4]
user=> (conj '(:a :b :c) \d)
(\d :a :b :c)
concat
edit(defn poly-expand
poly-expand [points]
(loop [aa (first points) remaining (rest points) built (empty points)]
(if (empty? remaining)
(concat built [aa (first points)])
(recur (first remaining) (rest remaining)
(concat built [aa (first remaining)])))))
(poly-expand '[a b c d])
-> [a b b c c d d a]
merge
editCombine two maps into a more massive map
(merge {:a 1} {:b 2}) => {:a 1, :b 2})
(merge-with + {:a 1} {:a 2, :b 3}) => {:a 3 :b 3}
Mapping Operators
editmap
edituser=> (map + [1 2 3 4] [1 2 3 4])
(2 4 6 8)
reduce
edituser=> (reduce * [2 3 4])
24
; sum the odd numbers to 100
;; Not so beautiful code, see next example for a better approach
(reduce #(+ %1 (if (= 1 (rem %2 2)) %2 0)) (range 100))
; sum the odd numbers to 100 (Cleaner version)
(reduce + (filter odd? (range 100)))
apply
edituser=> (apply str [1 2]) ; equivalent to (str 1 2)
"12"
user=> (let [pair (fn [a b] (str a " 'n "b))] (apply pair ["M" "Ms"]))
"M 'n Ms"
user=> (defn factorial [n]
(apply * (range 2 (inc n))))
#'user/factorial
user=> (factorial 5)
120