Wednesday, January 24, 2018

Clojure: simple closure

Given a positive integer n, return a function (f x) which computes x^n.
(((fn [n] (fn [x] (apply * (repeat n x)))) 2) 16)
256
or
((partial (fn [n x] (apply * (repeat n x))) 2) 16)
256

Tuesday, January 23, 2018

Clojure: intersection implementation

((comp set filter) #{0 1 2 3} #{2 3 4 5})
#{3 2}

Sunday, January 21, 2018

Clojure: map construction

((fn [kvect, vvect] (apply hash-map (interleave kvect vvect))) [:a :b :c] [1 2 3])
{:c 3, :b 2, :a 1}

Thursday, January 18, 2018

Clojure: split-at implementation

((juxt take drop) 2 [[1 2] [3 4] [5 6]])
[([1 2] [3 4]) ([5 6])]

Wednesday, January 17, 2018

Clojure: replicate elements in sequence

((fn [s n] (mapcat (fn [x] (repeat n x)) s)) [1 2 3] 2)
((1 1 2 2 3 3))

Clojure: interleave implementation

((fn interlive [s1 s2] (mapcat vector s1 s2)) [:a :b :c] [1 2 3])
(:a 1 :b 2 :c 3)

Clojure: flatten implementation

((fn flat [s] (if (sequential? s) (mapcat flat s) [s])) '((1 2) 3 [4 [5 6]]))
(1 2 3 4 5 6)

Monday, January 15, 2018

Clojure: remove consecutive duplicates from a sequence

(#(map first (partition-by identity %)) [1 1 2 3 3 2 2 3])
[1 2 3 2 3]

Clojure: factorial function

(#(reduce * (range 1 (+ 1 %))) 3)
6

Saturday, January 13, 2018

Clojure: generate Fibonacci sequence

((fn [n] (map second (take n (iterate (fn [[a b]] [b (+ a b)]) [0 1])))) 6)
(1 1 2 3 5 8)

Clojure: build map from value and keys sequence

((fn [defval vect] (reduce (fn [m k] (conj m {k defval})) {} vect)) 0 [:a :b])
{:a 0, :b 0}
or
((fn [defval vect] (zipmap vect (repeat defval))) 0 [:a :b :c])
{:a 0, :b 0, :c 0}

Clojure: inc map values

Source: Braveclojure
(reduce (fn [m [k v]] (assoc m k (inc v))) {} {:a 1 :b 2})
{:a 2, :b 3}
NB: In this example, reduce treats the argument {:a 1 :b 2} as a sequence of vectors, like ([:a 1] [:b 2])

or, with reduce-kv
(reduce-kv (fn [m k v] (assoc m k (inc v))) {} {:a 1 :b 2})
{:a 2, :b 3}