-
-
Notifications
You must be signed in to change notification settings - Fork 199
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
map(Traversable, callable) doesn't return a Traversable? #37
Comments
Reason is, that depending on the Traversable implementation passed to map() I don't necessary know how to create the same Traversable (obviously). The reasons for "always return an array" are simplicity and consistency. |
That said, if you have a good idea how to change that behavior, I would be very interested. |
Is there a reason you would have to return the same kind of |
That’s true, could be anything like an ArrayIterator. But that would only add runtime costs so I am not sure how useful it would be. Also given that the PHP APIs like array_keys() and so on take, well, arrays, also returning arrays feels like the lowest common denominator. |
Here is a simple example that illustrates why returning an iterator performs better for some uses; admittedly I am not sure if the example is perfectly compatible with this repo but you should understand it: $data = new ArrayIterator(range(0, 1000)); //realistically obtained from somewhere else.
limit(map($data, function($value) { return 2 * value;}), 4); If you return a lazy iterator you only have to map 4 values; if you return an array you have to map all 1000 values and then limit the top 4. To be clear, I'm not arguing that you should change, I was mostly curious why you didn't take this approach as most functional languages use lazy evaluation for their utility functions like this. |
Very good example and I agree there are cases where it would work better. What Functional PHP could offer is set of functions under a different namespace that always returns iterators. Let me think a little more about it, any input is of course appreciated and thanks for the discussion so far. |
FYI there is also nikic/iter that always returns lazy iterators. |
Yep, a very nice library. |
Closing issue for now. |
I'm curious why map() when called with a traversable doesn't return a traversable? Seems odd. What's the design decision there? Simplicity?
The text was updated successfully, but these errors were encountered: