scala / scala-library-next

backwards-binary-compatible Scala standard library additions
Apache License 2.0
69 stars 17 forks source link

Add mapWithState #122

Open BalmungSan opened 2 years ago

BalmungSan commented 2 years ago

The signature would be something like:

def mapWithState[S, B](init: S)(f: (S, A) => (S, B)): Col[B]

Is not as common as mapWithIndex but is kind of handy and is very hard to implement generically without much boilerplate.

benhutchison commented 2 years ago

Id do this with a fold normally..And IMO the final state value needs to be exposed..

On Sat., 21 May 2022, 10:41 am Luis Miguel Mejía Suárez, < @.***> wrote:

The signature would be something like:

def mapWithState[S, B](init: S)(f: (S, A) => (S, B)): Col[B]

Is not as common as mapWithIndex but is kind of handy and is very hard to implement generically without much boilerplate.

— Reply to this email directly, view it on GitHub https://github.com/scala/scala-library-next/issues/122, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAAXJZGCGN5PUGC6N3UYHGLVLAWLDANCNFSM5WQ747RA . You are receiving this because you are subscribed to this thread.Message ID: @.***>

BalmungSan commented 2 years ago

Id do this with a fold normally

The thing is that now you have to construct the new collection by yourself which is redundant and error-prone but also it may be more inefficient than the underlying map

And IMO the final state value needs to be exposed

Yeah, that is a good idea.

PS: For the record, fs2 has this function, is called mapAccumulate And I am creating a PR to add it to cats.

He-Pin commented 1 year ago

mapAccululate or mapAccumulation or statefulMap

sageserpent-open commented 10 months ago

Just mentioned this here: https://users.scala-lang.org/t/idiomatic-map-combined-with-fold/9628, which lead me here. Had the need for this on several occasions.