跳转到内容

Clojure 编程/示例/API 示例/序列

来自维基教科书,开放世界中的开放书籍

interpose

[编辑 | 编辑源代码]
user=> (apply str (interpose "|" ["hi" "mum" "and" "dad"]))
"hi|mum|and|dad"

interleave

[编辑 | 编辑源代码]
user=> (interleave [1 2 3] [:a :b :c])
(1 :a 2 :b 3 :c)
user=> (reverse [1 2 3])
(3 2 1)
user=> (apply str (interpose " " (reverse (.split "I am cold" " "))))
"cold am I"
user=> (butlast "hello")
(\h \e \l \l)
user=> (next [1 2 3 4 5])
(2 3 4 5)
user=> (nfirst [[1 2 3] [4 5 6] [7 8 9]])
(2 3)
user=> (nnext [1 2 3 4 5])
(3 4 5)
user=> (second [:a \b "c"])
\b
user=> (nth [1 2 3 4 5] 3)
4
user=> (replace {\l ""} "hello world")
(\h \e "" "" \o \space \w \o \r "" \d)
user=> (apply str (replace {\l ""} "hello world"))
"heo word"

序列构建

[编辑 | 编辑源代码]
user=> (conj [1 2 3] 4)
[1 2 3 4]

user=> (conj '(:a :b :c) \d)
(\d :a :b :c)
(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 {:a 1} {:b 2}) => {:a 1, :b 2})
(merge-with + {:a 1} {:a 2, :b 3}) => {:a 3 :b 3}

映射操作符

[编辑 | 编辑源代码]
user=> (map + [1 2 3 4] [1 2 3 4])
(2 4 6 8)
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)))
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
华夏公益教科书