liveBook · Manning

Take-last

As explained in Clojure: The Essential Reference

take-last is a Clojure function that returns the specified number of elements from the end of a sequence.

take-last returns a sequence containing the specified number of elements from the end of a sequential input. The count argument is required; zero or negative counts behave like zero. Unlike take, take-last has no transducer form and is not fully lazy. section 10.2

Use take-last when selection should keep the tail rather than the head:

  • Pair it with take to retain the final portion of a bounded prefix. section 10.2
  • Contrast it with drop-last, which removes the tail while retaining the head. section 10.2
  • Expect a sequential result; a non-sequential input raises IllegalArgumentException. section 10.2

Evaluation of a lazy source

Applying (take-last 1 (take 10 (xs))) to a source that prints a dot for each realized element prints ten dots before returning. The operation therefore evaluates the bounded input rather than behaving as a fully lazy head selector. section 10.2

Table 10.2. A summary of the functions available to extract a portion of a sequence.

Name

Description

Transducible?

Fully lazy?

drop

Drops the first n elements.

Yes

Yes

drop-while

Drops items until the given predicate returns false.

Yes

Yes

drop-last

Drops the last n elements (default to 1).

No

Yes

take

Keeps the first n elements, drops the rest.

Yes

Yes

take-while

Keeps element until the given predicate returns false.

Yes

Yes

take-last

Keeps the last n elements (no default for n).

No

No

nthrest

Like drop with inverted arguments. Never returns nil.

No

No

nthnext

Like nthrest but returns nil if beyond input length.

No

No

Compare take-last with neighboring sequence-selection functions by direction, transducibility, and laziness. section 10.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines the tail-selection contract and evaluation behavior, but does not develop implementation internals.
Examples
Uses a printing lazy source and contrasts take-last with neighboring sequence functions.
What it assumes
Assumes familiarity with Clojure sequences and distinguishes sequential inputs from transducer contexts.
What you can do after
Apply it to retain a bounded sequence suffix while accounting for its non-transducer and non-fully-lazy behavior.
How it connects
Connects take-last with take, drop-last, drop, nthrest, nthnext, sequences, and transducers.

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.