Jump to content

Clojure Programming/Examples/API Examples/Sequences

From Wikibooks, open books for an open world

interpose

[edit | edit source]
user=> (apply str (interpose "|" ["hi" "mum" "and" "dad"]))
"hi|mum|and|dad"

interleave

[edit | edit source]
user=> (interleave [1 2 3] [:a :b :c])
(1 :a 2 :b 3 :c)

reverse

[edit | edit source]
user=> (reverse [1 2 3])
(3 2 1)
user=> (apply str (interpose " " (reverse (.split "I am cold" " "))))
"cold am I"

butlast

[edit | edit source]
user=> (butlast "hello")
(\h \e \l \l)
user=> (next [1 2 3 4 5])
(2 3 4 5)

nfirst

[edit | edit source]
user=> (nfirst [[1 2 3] [4 5 6] [7 8 9]])
(2 3)

nnext

[edit | edit source]
user=> (nnext [1 2 3 4 5])
(3 4 5)

second

[edit | edit source]
user=> (second [:a \b "c"])
\b
user=> (nth [1 2 3 4 5] 3)
4

replace

[edit | edit source]
user=> (replace {\l ""} "hello world")
(\h \e "" "" \o \space \w \o \r "" \d)
user=> (apply str (replace {\l ""} "hello world"))
"heo word"

Sequence Building

[edit | edit source]
user=> (conj [1 2 3] 4)
[1 2 3 4]

user=> (conj '(:a :b :c) \d)
(\d :a :b :c)

concat

[edit | edit source]
(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

[edit | edit source]

Combine 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

[edit | edit source]
user=> (map + [1 2 3 4] [1 2 3 4])
(2 4 6 8)

reduce

[edit | edit source]
user=> (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

[edit | edit source]
user=> (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