medley icon indicating copy to clipboard operation
medley copied to clipboard

Add mapcat-indexed function

Open tomdl89 opened this issue 10 months ago • 2 comments

I feel this fits with medley pretty well. It exists in Kotlin as flatMapIndexed which I've used a few times recently, and realised is missing from clojure.core. It also exists in JS as the dyadic form of flatMap. It's useful for conditionally inserting extra items based on index, among other things. e.g.

(mapcat-indexed (fn [i x] (if (even? i) [x :break] [x]))
                '[a b c d e f g h i j h])
;; => (a :break b c :break d e :break f g :break h i :break j h :break)

lmk what you think :)

tomdl89 avatar Jun 24 '25 12:06 tomdl89

I'm unsure about this one. While it could potentially be useful, it doesn't save a whole lot of typing, and the use-case doesn't seem that common:

(mapcat-indexed f)
(comp (map-indexed f) cat)

(mapcat-indexed f coll)
(sequence (comp (map-indexed f) cat) coll)
(transduce (map-indexed f) into coll)

And if mapcat-indexed is added, what about filter-indexed etc.?

weavejester avatar Jun 24 '25 12:06 weavejester

Agreed it doesn't save a whole lot of typing, but I doubt I'm alone in often forgetting which order to put the functions in for comp, and it does read more nicely, with less nesting.

I wouldn't be opposed to adding filter-indexed, remove-indexed and keep-indexed but see your point that including one of the 4 seems somewhat arbitrary, and including all 4 threatens medley's compactness.

I won't make a strong argument on this one. I enjoy coding up these PRs, so it's no time wasted for me. Happy to leave it on the backburner or close entirely :)

tomdl89 avatar Jun 24 '25 13:06 tomdl89