[BONUS]
doseqIn Clojure, we can say every data structure is a sequence. So far, we learned
vectorandmap, both of which are sequence. String is also a sequence. When something is seq-able, it is a sequence.
first item or not If something is seq-able, it returns the first item in the sequence by the
firstfunction. This is a good test whether it is a sequence or not.
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 tomapfunction we have already studied.
The
doseqfunction takes two parameters: 1. The sequence of things, for instance, a vector 2. A function which is repeatedly called with each element in the sequenceNotice that the first argument to
doseqspecifies 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))
Return to the first slide, or go to the curriculum outline.