Sunday, 29 July 2012

Focusing on Clojure

Back on Numbers

Numbers can be appended with letters that allow you to specify the type.

(type 1000)
java.lang.Long

(type 1000N)
clojure.lang.BigInt

(type 1000M)
clojure.lang.BigDecimal

Map, Reduce & Filter

These healthy staples allow you to apply functions to sequences. The usage is dependant on context. I'll go through each one:

Map

Map applies a function to a sequence of data and returns a sequence of the same length with the function applied to each

(map (fn [n] (* n 10)) '(1 2 3 4 5 6 7 8 9 10))
(10 20 30 40 50 60 70 80 90 100)

Functions with multiple arity can also be used. The result of this function is multiplying arg 1 with arg 2. This has given us a list of square numbers.

(map (fn [n m] (* n m)) (range 1 11) (range 1 11))
(1 4 9 16 25 36 49 64 81 100)

Reduce

Reduce is similar however instead of returning a list of the same size, the goal is to get to a single result. So arg 1 and arg 2 are used in combination to produce a single result, which then becomes arg 1 and #3 becomes arg 2. This is best shown with an example.

(reduce * (range 1 6))
120

To produce that output the following is equivalent:
((((1 * 2) * 3) * 4) * 5) * 6 = 120

Filter

Filter is again similar, however the size of the output is variable. You could end up with a list as long as the original or empty or anywhere in between. Filter works by providing a predicate function with the list and outputs the values of the list where the function returns a truthy value.

(filter even? (range 1 11))
(2 4 6 8 10)

ArrayList

Since clojure is on the JVM, it can work with java code seemlessly

(def x (java.util.ArrayList.))
(map #(.add x %) (range 1 11))
(true true true true true true true true true true)
x
#<ArrayList [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>

Sequential destructuring

Vectors can be sequentially destructured as demonstrated here

(def x [5 10 [3 5] 99.9])
[5 10 [3 5] 99.9]
(let [[a b _] x] (+ a b))
15

The & can also be used

(let [[a & rest] x] rest)
[10 [3 5] 99.9]

Date

Just as a quick reference, #inst "" can be used for quick date creation

(def d #inst "2012")
#inst "2012-01-01T00:00:00.000-00:00"
(type d)
java.util.Date

Repeatedly Partial

Lookup these values

(take 15 (repeatedly (partial rand-int 60)))
(48 18 41 4 41 49 45 22 0 25 17 57 45 36 52)

Others

Some other useful functions found are memoize, doseq, dotimes, for, range, doc, find-doc and source.

No comments:

Post a Comment