[BONUS]

Sequences and Loops

  • What are sequences
  • doseq

What are sequences?

In Clojure, we can say every data structure is a sequence. So far, we learned vector and map, both of which are sequence. String is also a sequence. When something is seq-able, it is a sequence.

If something is seq-able, it returns the first item in the sequence by the first function. This is a good test whether it is a sequence or not.

Results of first

(turtle-names)
;=> [:trinity :smith0 :smith1]  ; vector
(first (turtle-names))
;=> :trinity                    ; the first item

(:trinity (state))
;=> {:x 0, :y 0, :angle 90, :color [30 30 30]}  ; map
(first (:trinity (state)))
[:x 0]                                          ; the first item

(first "Hello, World!")  ; string
;=> \H                   ; the first item

(first :trinity)         ; keyword is not seq-able
;=> IllegalArgumentException Don't know how to create ISeq from:
clojure.lang.Keyword  clojure.lang.RT.seqFrom (RT.java:528)

doseq

Clojure is very good at iterate over a sequence. There are many functions that interact on sequences. The doseq(for do a sequence) is one of the well-used functions of such. This function works quite similar to map function we have already studied.

The doseq function takes two parameters: 1. The sequence of things, for instance, a vector 2. A function which is repeatedly called with each element in the sequence

Notice that the first argument to doseq specifies the sequence as an odd-looking vector: [variable value ...]. The number of elements in this vector need to be even, since the first element will be the variable and the next one will be evaluated for its value.

;; doseq example
(doseq [n (turtle-names)] (forward n 40))

EXERCISE

  • Twinkle Little Star (making sounds)
  • Turtles Walk (more function study)