Skip to content

Commit bbb5650

Browse files
authored
Merge pull request #120 from jasalt/document-for-while-reduce
document `for` together with `:when` and `:reduce`
2 parents cfc961b + 8233297 commit bbb5650

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

content/documentation/control-flow.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ have the form `:modifier argument`. The following modifiers are supported:
130130
* `:while` breaks the loop if the expression is falsy.
131131
* `:let` defines additional bindings.
132132
* `:when` only evaluates the loop body if the condition is true.
133-
* `:reduce [accumulator initial-value]` Instead of returning a list, it reduces the values into `accumulator`. Initially `accumulator` is bound to `initial-value`.
133+
* `:reduce [accumulator initial-value]` Instead of returning a list, it reduces the values into `accumulator`. Initially `accumulator` is bound to `initial-value`. Normally with `when` macro inside `reduce` function the accumulator becomes `nil` when the condition is not met. However with `for`, `:when` can be used for conditional logic with `:reduce` without this issue.
134134

135135
```phel
136136
(for [x :range [0 3]] x) # Evaluates to [0 1 2]
@@ -147,7 +147,9 @@ have the form `:modifier argument`. The following modifiers are supported:
147147
(for [[k v] :pairs {:a 1 :b 2 :c 3} :reduce [m {}]]
148148
(put m k (inc v))) # Evaluates to {:a 2 :b 3 :c 4}
149149
(for [[k v] :pairs {:a 1 :b 2 :c 3} :reduce [m {}] :let [x (inc v)]]
150-
(put m k x)) # Evaluates to {:a 2 :b 3 :c 4}
150+
(put m k x)) # Evaluates to {:a 2 :b 3 :c 4}
151+
(for [[k v] :pairs {:a 1 :b 2 :c 3} :when (contains-value? [:a :c] k) :reduce [acc {}]]
152+
(put acc k v)) # Evaluates to {:a 1 :c 3}
151153
152154
(for [x :in [2 2 2 3 3 4 5 6 6] :while (even? x)] x) # Evaluates to [2 2 2]
153155
(for [x :in [2 2 2 3 3 4 5 6 6] :when (even? x)] x) # Evaluates to [2 2 2 4 6 6]

0 commit comments

Comments
 (0)