(require '[clojure.string :as str])
(def numbers [2 3 5 7 11 13 17 19])
;; Clojure 没有 "break":循环只要不调用 recur 就会结束
(def s
(loop [[n & more] numbers, acc []]
(if (or (nil? n) (> n 10))
(str/join "-" acc)
(recur more (conj acc n)))))
;; s is "2-3-5-7"
(println "s is" s)
;; 在 reduce 内部,提前退出用 "reduced"
(println "with reduce:"
(str/join "-" (reduce (fn [acc n]
(if (> n 10) (reduced acc) (conj acc n)))
[]
numbers)))
;; 用声明式的写法则只是 take-while
(println "with take-while:" (str/join "-" (take-while #(<= % 10) numbers)))