purescript-arrays icon indicating copy to clipboard operation
purescript-arrays copied to clipboard

Implement zipWith3

Open TOTBWF opened this issue 5 years ago • 6 comments

TOTBWF avatar Jan 13 '20 23:01 TOTBWF

I'm not super keen on this actually: if we add zipWith3, then someone else will probably come along soon and ask for zipWith4, and so on. Is it not currently possible to implement this function with decent performance without increasing the API surface of this library?

hdgarrood avatar Jan 16 '20 18:01 hdgarrood

You can chain zipWith calls (it's apply for some hypothetical ZipArray), however you must traverse the Array for each call. It's likely possible to fuse this though with a new type.

natefaubion avatar Jan 16 '20 18:01 natefaubion

@hdgarrood Would you accept a PR for a generalized, fused ZipArray? @TOTBWF Would you be willing to try and implement this? I'm happy to help.

natefaubion avatar Jan 16 '20 19:01 natefaubion

Yes, that sounds great 👍

hdgarrood avatar Jan 16 '20 19:01 hdgarrood

Yeah, that sounds like a much better solution. I'll hopefully have something by the end of day.

TOTBWF avatar Jan 16 '20 21:01 TOTBWF

@natefaubion I took a shot at implementing this and quickly realised that a law abiding pure is impossible with strict arrays. If the result of pure is of a finite size N then it will fail the identity law

pure identity <*> arr ≠ arr

for any arr with length > N.

Do you have any suggestions for tackling that?

I came up with slightly different semantics for zip that seems to make it possible to have both applicative and monad instances, and wrote up a sample implementation. This version of zip doesn't drop elements when one of the arrays is bigger than the other. Instead, it extends the shorter array by repeating its last element.

As far as I can tell, this satisfies the applicative and monad laws, and is still useful. For example, you can zip together arrays of the same size and get results identical to regular zip. There are other constructions that I considered, but this one has the advantage of being a newtype over Arrays.

Thoughts?

ajnsit avatar Dec 10 '21 13:12 ajnsit