maplist for core?

149 views
Skip to first unread message

Marc Dzaebel

unread,
Sep 30, 2012, 10:51:46 AM9/30/12
to clo...@googlegroups.com
I often have the need to lazily iterate over rests of lists rather than elements. I frequently saw discussions about this topic. In CL it's called maplist, in Haskell it's tails (Scala missing?). Of course there are several methods to do this, e.g. (take-while identity (iterate next S)), but if you use them recursivly, code reads badly. So my proposal would be to have a kind of following function in the core:

(defn maplist
  ([s] (maplist identity s))
  ([f s] (when-let [s (seq s)] (lazy-seq (cons (f s) (maplist f (next s)))))))
;(maplist [1 2 3]) -> ((1 2 3) (2 3) (3))


Questions:
  1. Would such a method help more developers?
  2. Is there a conceptional reason, to omit a maplist equivalent in Clojure?

Thanks, Marc

Stuart Sierra

unread,
Sep 30, 2012, 11:13:51 AM9/30/12
to clo...@googlegroups.com
Never had a use for such a thing, myself, but it sounds like a reasonable candidate for https://github.com/clojure/core.incubator at least.
-S

Ben Wolfson

unread,
Sep 30, 2012, 12:22:13 PM9/30/12
to clo...@googlegroups.com
If maplist/tails, why not inits as well?

Prelude GOA Data.List> inits [1,2,3]
[[],[1],[1,2],[1,2,3]]

I've also found haskell's unfold useful:

(defn expand ;; since Clojure has "reduce" and not "foldl"
[f seed]
(lazy-seq (when-let [[a b] (f seed)] (cons a (expand f b)))))

As with maplist it can be implemented in terms of iterate, though I
think that implementation is unattractive. (And iterate can be
implemented in terms of it),
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clo...@googlegroups.com
> Note that posts from new members are moderated - please be patient with your
> first post.
> To unsubscribe from this group, send email to
> clojure+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en



--
Ben Wolfson
"Human kind has used its intelligence to vary the flavour of drinks,
which may be sweet, aromatic, fermented or spirit-based. ... Family
and social life also offer numerous other occasions to consume drinks
for pleasure." [Larousse, "Drink" entry]

Marc Dzaebel

unread,
Sep 30, 2012, 4:30:47 PM9/30/12
to clo...@googlegroups.com
expand looks really useful too.

Marc Dzaebel

unread,
Sep 30, 2012, 4:33:06 PM9/30/12
to clo...@googlegroups.com
Well, I might have to collect usecases.
Reply all
Reply to author
Forward
0 new messages