The Clojure sequence library - a short introduction

The Clojure sequence library - a short introduction

@kevin_noonan

Clojure Ireland

27th Nov 2013, Dublin

braveclojure.com

Clojure collection types

Lists with round brackets

'("sky", "blue", "tropical", "waterfall")

Vectors with square brackets

[ "bumpy", "ride", "in", "a", "canoe" ]

Commas are optional. (They're ignored by Clojure.)

[ "bumpy" "ride" "in" "a" "canoe" ]

Sets with curly brackets

#{ "tulip", "rose", "orchid" }

Maps with curly braces and entries in pairs.

{ :first "Ron" :last "Burgundy" :position "Anchorman" }

A keyword is preceded with a colon

:surname

{ :first "Ron",
:last "Burgundy",
:position "Anchorman" }

(def employee { :first "Ron"
:last "Burgundy"
:position "Anchorman" } )

( :position employee )

"Anchorman"

( employee :position )

"Anchorman"

The preceding types are endlessly composable...

Lists of maps;
sets containing vectors;
maps of vectors of maps, etc.

(range 10)

(0 1 2 3 4 5 6 7 8 9)

Apostrophe to prevent evaluation

(def unsorted '( "pear" "peach" "kiwi" "banana" "apple" "plum" ))

(sort unsorted)

("apple" "banana" "kiwi" "peach" "pear" "plum")

(def dreamtokens '("sky", "blue", "tropical", "waterfall"))

The apostrophe stops the first item in a list being treated as a function.

(first dreamtokens)

"sky"

(rest dreamtokens)

("blue", "tropical", "waterfall")

(nth dreamtokens 3)

"waterfall"

(count dreamtokens)

4

(drop 2 dreamtokens)

("tropical" "waterfall")

(take 2 dreamtokens)

("sky" "blue")

(reverse dreamtokens)

("waterfall" "tropical" "blue" "sky")

(map count dreamtokens)

(3 4 8 9)

(first (map reverse dreamtokens))

(\y \k \s)

(def wordcounts '(3 4 8 9))

(reduce + wordcounts)

24

(reduce + 0 wordcounts)

24

(reduce + (map count dreamtokens))

24

(filter #(> (count %) 5) dreamtokens)

("tropical" "waterfall")

(some #(< (count %) 3) dreamtokens)

nil

(some #(< (count %) 4) dreamtokens)

true

(def dreamcount (map count dreamtokens))

(zipmap dreamtokens dreamcount )

{"waterfall" 9, "tropical" 8, "blue" 4, "sky" 3}

Remember that the sequence library is endlessly composable...

...and is much bigger than I've had time to show.

clojure.org/sequences

Questions

@kevin_noonan

/

#