markrogoyski / itertools-php

PHP Iteration Tools Library
MIT License
140 stars 11 forks source link

Shouldn't `Multi.zip()` throw exceptions for collections of different sizes? #1

Closed danon closed 1 year ago

danon commented 2 years ago

I supposed zipping of collections like in python is supposed to work for collections that are of the same size. If they are different, I think it would be a good idea to throw an exception in that case.

BTW, cool library, nice ReadMe.md and good tests!

markrogoyski commented 2 years ago

Hi @Danon,

Thanks for your kind words and interest in IterTools PHP.

For zipping iterables that are different sizes, I think you can make a good argument for both throwing exceptions and iterating as much as you can. The behavior that the library has for zip is to iterate up until the point that the shortest input iterable is exhausted. Python's built-in zip function was the original inspiration for this library--I wanted something similar in PHP. So for IterTools PHP's zip function, I went with Python's behavior because it is well known and provides the most flexibility in how you can use it. Also, each use case is different. For the cases where this is not desirable, the application code could simply check the input sizes prior to zipping and throw the exception there.

FYI: Here is how Python works zipping iterables of different sizes:

>>> for x, y in zip([1, 2, 3], ['a', 'b']):
...     print(x, y)
...
1 a
2 b
>>> for x, y in zip([1, 2], ['a', 'b', 'c']):
...     print(x, y)
...
1 a
2 b

The library also provides a Multi::zipLongest function that will iterate every element of the largest iterable if one has more than another, providing null values for the iterables that run out of data. So there are multiple ways to deal with zipping inputs of different sizes.

Thanks again for your interest in IterTools PHP! Mark

danon commented 2 years ago

@markrogoyski

You could design API in sucha a way:

But of course, that's your library and your decision, so I'm not gonna push it, just asking.

To me, throwing exception is more natural, I rarely ever zip collections of different sizes, so I would prefer the exception. I'm leaving the decision to you.