Zulip Chat Archive

Stream: Is there code for X?

Topic: folding while mapping?


Thomas Murrills (Nov 08 2023 at 22:49):

Is there a conventional functional programming name for this function? Does it exist already somewhere?

def foldlMap (f : β  α  (γ × β)) (init : β) (as : Array α) : Array γ × β := Id.run do
  let mut gs := Array.mkEmpty as.size
  let mut b := init
  for a in as do
    let (g,b') := f b a
    b  := b'
    gs := gs.push g
  return (gs, b)

Kyle Miller (Nov 09 2023 at 00:19):

docs#List.mapAccumr is the list version for foldr

Kyle Miller (Nov 09 2023 at 00:20):

I know that the Mathematica name for your function is FoldList, though it starts with gs := #[init].

Thomas Murrills (Nov 09 2023 at 00:21):

I'm looking for the analogue of FoldPairList, haha!

Thomas Murrills (Nov 09 2023 at 00:27):

(Though actually that's even slightly different as well, since it doesn't return the final accumulated value)

Thomas Murrills (Nov 09 2023 at 00:32):

Just guessing, but maybe the typical FP strategy here is just to mapM in a state monad, since that's what this is, but it can sometimes be convenient to not have to StateT things...either that or there is no typical strategy, perhaps because for whatever reason people wind up not really having to do this that often.


Last updated: Dec 20 2023 at 11:08 UTC