In [1]:
; lazy infinite sequence with recursive definition
(def fib-seq-lazy 
  ((fn rfib [a b] 
     (lazy-seq (cons a (rfib b (+ a b)))))
   0 1))
(take 20 fib-seq-lazy)
Out[1]:
[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]
In [2]:
; 'unless' cannot be defined with a function because
; it does not always evaluate both its arguments.
(defmacro unless [pred a b]
  `(if (not ~pred) ~a ~b))
(unless false (println "Will print") (println "Will not print"))
Will print
Out[2]:
null
In [2]:
(defn run [nvecs nitems nthreads niters]
  (let [vec-refs (vec (map (comp ref vec)
                           (partition nitems (range (* nvecs nitems)))))
        swap #(let [v1 (rand-int nvecs)
                    v2 (rand-int nvecs)
                    i1 (rand-int nitems)
                    i2 (rand-int nitems)]
                (dosync
                 (let [temp (nth @(vec-refs v1) i1)]
                   (alter (vec-refs v1) assoc i1 (nth @(vec-refs v2) i2))
                   (alter (vec-refs v2) assoc i2 temp))))
        report #(do
                 (prn (map deref vec-refs))
                 (println "Distinct:"
                          (count (distinct (apply concat (map deref vec-refs))))))]
    (report)
    (dorun (apply pcalls (repeat nthreads #(dotimes [_ niters] (swap)))))
    (report)))
; When run, we see no values get lost or duplicated in the shuffle.
; There are 36 distinct numbers before and after. 
(run 6 6 6 100000)
([0 1 2 3 4 5] [6 7 8 9 10 11] [12 13 14 15 16 17] [18 19 20 21 22 23] [24 25 26 27 28 29] [30 31 32 33 34 35])
Distinct: 36
([17 2 16 26 24 25] [11 28 27 3 23 35] [34 21 8 31 7 19] [20 0 30 15 1 12] [29 22 32 13 6 14] [5 10 18 4 9 33])
Distinct: 36
Out[2]:
null
In [ ]: