liveBook · Manning

takeWhile

As explained in Clojure: The Essential Reference

take-while is a Clojure function that returns the longest prefix of a sequence whose elements satisfy a predicate or returns a transducer that keeps that prefix.

take-while returns the longest prefix of a sequential input whose elements satisfy a one-argument predicate. It stops at the first element for which the predicate is false; with only the predicate, it returns a transducer instead of immediately processing a collection. section 10.2

Use the two arities according to the processing style:

  • `(take-while pred coll)` returns a lazy sequence containing matching elements from the head of `coll`. section 10.2
  • `(take-while pred)` returns a transducer that terminates reduction when the predicate fails. section 7.2
  • `pred` must accept one argument and return logical true or false; `coll` may be any seqable input or `nil`. section 10.2
  • The result contains no elements after the first predicate failure, even when later elements would satisfy the predicate. section 10.2

Tokenizing consecutive matching runs

A tokenizer can combine `drop-while` and `take-while` to extract consecutive runs. For `(tokenize odd? '(1 4 1 5 9 2 6 4 3 5 8 9 3 2 6))`, the result is `((1) (1 5 9) (3 5) (9 3))`.

How Clojure: The Essential Reference covers it

How deep it goes
Defines predicate, input, output, arities, laziness, and stopping behavior, while deferring implementation internals.
Examples
Demonstrates odd-number tokenization and places take-while among equivalent sequence-selection forms.
What it assumes
Assumes familiarity with Clojure predicates, sequences, lazy processing, and reducing functions while specifying the collection contract.
What you can do after
Apply take-while to extract matching prefixes or compose its predicate-based transducer into a reduction pipeline.
How it connects
Connects take-while with predicates, sequences, transducers, drop-while, and other contiguous sequence-selection functions.

Also explained in

Compare how 2 books explain takeWhile →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.