Looping
Convenient side-effecty looping over data structures:
each
: loop over each value in a dseachk
: loop over each key in a dseachp
: loop over each pair in a ds
plus:
loop
: General looping (useseq
similarly for list comprehensions)while
for
: C-style looping
# Arrays --------------------
def a @[44 55 66])
(
# 44, 55, 66
(each e a (pp e)) # 0, 1, 2
(eachk i a (pp i)) # 2-element tuples:
(eachp p a (pp p)) # (0 44)
# (1 55)
# (2 66)
# Or unpack the indices and elements as you go:
"-->" e)))
(eachp [i e] a (pp (string i
# Tables --------------------
def t @{:a 1 :b 2 :c 3})
(
# 3, 1, 2
(each v t (pp v)) # :c, :a, :b
(eachk k t (pp k)) # 2-element tuples:
(eachp p t (pp p)) # (:c 3)
# (:a 1)
# (:b 2)
# Or unpack the keys and values as you go:
"-->" v)))
(eachp [k v] t (pp (string k
# Strings --------------------
# Those all also work on strings too, where the values are
# decimal integer byte values.
# General looping --------------------
# The loop "head" is the tuple it starts with. The head may
# contain
#
# - "bindings" (3 parts: "binding :verb object/expression") and
# - "conditionals" (2 parts: ":modifier argument").
range [4 7]] # loop head contains one binding
(loop [n :# 4, 5, 6
(pp n))
range [1 7] # binding
(loop [n :# conditional
:when (odd? n) + n 10)]] # conditional
:let [m ("--" m)))
(pp (string n # "1--11"
# "3--13"
# "5--15"
range [1 5] # binding
(loop [n :range [14 16]] # binding
m :"--" m)))
(pp (string n # "1--14"
# "1--15"
# "2--14"
# "2--15"
# "3--14"
# "3--15"
# "4--14"
# "4--15"
in [22 33 44]]
(loop [x :
(pp x))# 22
# 33
# 44
1 :b 2 :c 3}]
(loop [x :pairs {:a
(pp x))# (:c 3)
# (:a 1)
# (:b 2)
1 :b 2 :c 3}]
(loop [[k v] :pairs {:a "--" v)))
(pp (string k # "c--3"
# "a--1"
# "b--2"
# Use `:iterate` to tell the loop how to compute
# the next local loop value (here, `i`).
2)
(var n * 2 x))
(defn foo [x] (
(loop [i :iterate (foo n)while (< n 1000)
:set n i)]
:after (
(pp i))
# though, you could also accomplish that with:
while (< n 1000)
(
(pp n)set n (foo n)))
(
# or
for _ 1 10
(
(pp n)set n (foo n)))
(
# And speaking of `for`...
# C-style looping --------------------
for i 0 5 (pp i)) # counts 0 to 4 (
Where there’s no side-effects, you can do list comprehensions with seq
, which otherwise works similarly to loop
.