Clojure Programming/Examples/API Examples/Sequences

From Wikibooks, open books for an open world
Jump to: navigation, search

interpose[edit]

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

interleave[edit]

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

reverse[edit]

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

butlast[edit]

user=> (butlast "hello")
(\h \e \l \l)

next[edit]

user=> (next [1 2 3 4 5])
(2 3 4 5)

nfirst[edit]

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

nnext[edit]

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

second[edit]

user=> (second [:a \b "c"])
\b

nth[edit]

user=> (nth [1 2 3 4 5] 3)
4

replace[edit]

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]

conj[edit]

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

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]

map[edit]

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

reduce[edit]

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]

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