mapcat is too eager

Description

The following expression prints 1234 and returns 1:

The reason is that (apply concat args) is not maximally lazy in its arguments, and indeed will realize the first four before returning the first item. This in turn is essentially unavoidable for a variadic concat.

This could either be fixed just in mapcat, or by adding a new function (to clojure.core?) that is a non-variadic equivalent to concat, and reimplementing mapcat with it:

Environment

None

Activity

Show:
gfredericks
June 17, 2013, 1:54 PM

I realized that concat could actually be made lazier without changing its semantics, if it had a single [& args] clause that was then implemented similarly to join above.

John Jacobsen
July 27, 2013, 2:08 PM

I lost several hours understanding this issue last month [1, 2] before seeing this ticket in Jira today... +1.

[1] http://eigenhombre.com/2013/07/13/updating-the-genome-decoder-resulting-consequences/

[2] http://clojurian.blogspot.com/2012/11/beware-of-mapcat.html

gfredericks
February 5, 2014, 7:35 PM

Updated join code to be actually valid.

Ghadi Shayban
May 22, 2015, 2:32 AM

The version of join in the description is not maximally lazy either, and will realize two of the underlying collections. Reason: destructuring the seq results in a call to 'nth' for 'x' and 'nthnext' for 'xs'. nthnext is not maximally lazy.

Ghadi Shayban
May 2, 2017, 4:47 PM

Though the docstring makes no lazyiness promises (except declaring its specific implementation), this seems like a defect, not an enhancement. mapcat realizes 4 underlying collections at minimum:

Assignee

Unassigned

Reporter

gfredericks

Labels

Approval

Triaged

Patch

Code and Test

Affects versions

Priority

Minor