Tuesday 2 June 2015

Living clojure - day 2

Sequences - rest

The docs have this to say about rest — Returns a possibly empty seq of the items after the first. Calls seq on its argument.

(= [20 30 40] (rest [10 20 30 40]))

Intro to Functions

(= 8 ((fn add-five [x] (+ x 5)) 3))

Double Down

(= (* 2 2) 4)

Hello World

(= ((fn name [name] (str "Hello, " name "!")) "Dave") "Hello, Dave!")

Sequences: map

I’ve used this in Python and JavaScript. Map takes a function and “collectiony” thing to which it applies the function for each thing in the collections. The first answer is right and more succinct but the second one demonstrates a tighter grip on the concept. The %acts as a placeholder for the value generated from the collection.

(= [6 7 8] (map #(+ % 5) '(1 2 3)))
(= (map #(+ % 1) '(5 6 7)) (map #(+ % 5) '(1 2 3)))

Sequences: filter

Filter is straight forward like map. It takes a predicate and a collection. I could have answered '(6 7 8) but the answer I’ve provided, whilst more verbose flexes my filter muscles.

(= (filter #(< % 8) '(6 7 8 9 10)) (filter #(> % 5) '(3 4 5 6 7)))

Local bindings

The simplest answer to this was 7, but that’s no fun.

(= (let [x 6] (+ 1 x)) (let [x 5] (+ 2 x)))

Let it Be

(= 10 (let [x 7 y 3 z 1] (+ x y)))
(= 4 (let [x 7 y 3 z 1] (+ y z)))
(= 1 (let [x 7 y 3 z 1] z))

And that is day two.