lehins / massiv

Efficient Haskell Arrays featuring Parallel computation
BSD 3-Clause "New" or "Revised" License
386 stars 23 forks source link

Monadic version of ``makeArray`` and friends? #52

Closed kozross closed 5 years ago

kozross commented 5 years ago

I might be missing it, but I can't seem to find anything like a monadic version of a construction function. Something of the form:

makeArrayM :: (Monad m, Construct r ix e) => Comp -> ix -> (ix -> m e) -> m (Array r ix e)

I understand that this might not be workable with every representation type, but D should be possible, right? As current, the only way I see to do this is to go via fromList and friends. Is there something I'm missing here?

lehins commented 5 years ago

Hey @kozross, there is a good reason why you can't find monadic version of array construction. This issue has been brought up before in #5, which I was able to solve and implemented a very fast version for monadic array creation and mapping, or so I thought, until #24

So the naive version that works, but is very slow, is to convert an array from/to a list and do monadic operations directly on list, just as you suggested. A better way is to convert it from/to a vector and use generateM and mapM on the vector itself, which should be faster.

While there is a way to work around with manifest representations by the means of conversion to other data structures as described above, on the contrary, it's not possible to implement makeArrayM for D representation at all.

I still want to come up with a way to do monadic operations natively in massiv, but unfortunately it is much trickier than it looks. I'll keep that ticket open until we get some sort of solution for it.

kozross commented 5 years ago

@lehins Thanks for that - I can work in U, so I will try generateM and mapM as you suggested.

lehins commented 5 years ago

We still need applicative version: traverse et al:

Also convenience functions:

Moreover, it looks like we can do better than just simply go through lists: https://stackoverflow.com/questions/53770035/is-it-safe-to-interleave-manual-realworld-state-passing-with-an-arbitrary-monad

lehins commented 5 years ago

This has been implemented in 0.2.6.0