Clojure Koans: Lists


Hey guys! In this episode, we are going to go over lists. I have lein koan running.

So lets jump right it!

“Lists can be expressed by function or a quoted form”
(= ‘(__ __ __ __ __) (list 1 2 3 4 5))

1 2 3 4 5

That makes sense!

“They are Clojure seqs (sequences), so they allow access to the first”
(= __ (first ‘(1 2 3 4 5)))

1

No need in looking up first :)

“As well as the rest”
(= __ (rest ‘(1 2 3 4 5)))

2 3 4 5

“Count your blessings”
(= __ (count ‘(dracula dooku chocula)))

We looked up count in the previous episode. All it does is count the items in the sequence.

3

“Before they are gone”
(= __ (count ‘()))

0

“The rest, when nothing is left, is empty”
(= __ (rest ‘(100)))

‘() An empty list.

“Construction by adding an element to the front is easy”
(= __ (cons :a ‘(:b :c :d :e)))

‘(:a :b :c :d :e).

The technical definition of cons: Returns a new seq where x is the first element and seq is the rest.

“Conjoining an element to a list isn’t hard either”
(= __ (conj ‘(:a :b :c :d) :e))

The thing about conj is that on a list that it will only conjoin on the front were as on a vector, it will conjoin on the back. Something to look out for.

‘(:e :a :b :c :d)

“You can use a list like a stack to get the first element”
(= __ (peek ‘(:a :b :c :d :e)))

Peek allows you to use the list as a stack.

:a

“Or the others”
 (= __ (pop ‘(:a :b :c :d :e)))

:b :c :d :e

“But watch out if you try to pop nothing”
(= __ (try 
(pop ‘())
(catch IllegalStateException e
“No dice!”)))

“No dice!”

“The rest of nothing isn’t so strict”
(= __ (try 
(rest ‘())
(catch IllegalStateException e
“No dice!”))))

‘()

This will return a list.

With that we have completed the third koan!


One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.