practicalli / practicalli/clojure

clojure.core/for examples

Open
#325 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

clojure-core
Dominant language
Makefile
Stars
117
Forks
36
PR merge metrics
No merged PRs in 30d

Description

for is lazy and can be terminated

I'm iterating an integer vector twice checking for specific sum, but would like to stop once I find a first match. How would one do that?

(defn find-all-sums-to-2020 [expenses]
  (for [x expenses, y (rest expenses)
        :let [sum (+ x y)]
        :when (= sum 2020)]
    [x y]))(defn find-sum-to-2020 [expenses]
  (first (find-all-sums-to-2020 expenses)))

for is not a loop, but it is lazy, you can just stop consuming it
there's also the :while arg (edited)
what you are doing there is the normal way to stop it early

So (first) function will evaluate only the first result and therefore stop the inner for from continuing, is that what you are saying?

right, more precisely it never asks the inner for another value, so the value isn't calculated
that's how laziness works - you don't stop it from the outside, you just never force it to execute, so it doesn't

the distinction becomes important when you have chunking (so asking for one item might make it decide to calculate 32 items) - you aren't forcing it to stop, you're asking it to calculate

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the clojure.core/for example and the discussion of first and lazily consuming the first result. Clarify the example so it explains how taking the first match affects evaluation and notes the chunking caveat. Done means the example and explanation clearly answer how to stop after the first match.

Written by the indexing model from the issue text.

Assessment

Tech stack
clojure
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.