Home > OS >  Haskell: scan an Array
Haskell: scan an Array

Time:10-10

I have an Array of Foos:

myArray :: Array Int Foo

I would like to "scan" it from left to right using a function similar to:

getNextStep :: Bar -> Foo -> Bar

I would like to scan myArray to generate an array of Bars:

scanl :: (Bar -> Foo -> Bar) -> Bar -> Array Int Foo -> Array Int Bar

Yes, this is very similar to prelude's scanl. But is there a version for Arrays? Can I build one with e.g. Traversable? Thanks

CodePudding user response:

mapAccumL works on any Traversable. It's a bit more general than a scan but if you use a step function that emits the state value unchanged you more or less get a scan again.

> mapAccumL (\s x -> (s   x, s)) 0 [1,2,3,4]
(10,[0,1,3,6])

You'd have to add the final element back on to the array if you wanted it to be included like it is with scanl. Traversables in general don't have a way to add an element, so we can't make that work for any traversable.

  • Related