3 ms·
"(which, for some reason, don't take an optional predicate)" This kills me pretty much every time I use those functions. It seems like 9 times out of 10, I nee
by mccutchen 17y ago
"(which, for some reason, don't take an optional predicate)"
This kills me pretty much every time I use those functions. It seems like 9 times out of 10, I need the ability to pass in a predicate function.
This always struck me as a major oversight... does anyone know if this design decision was made for a particular reason?
- kragen 17y agoYou want to be able to say all(items, lambda x: x.is_cool()) instead of all(item.is_cool() for item in items)? The second one seems clearer to me and isn't substantially longer.
- mccutchen 17y agoGood point. I guess usually crops up when I've already got a predicate function handy and I want to say `all(items, f)`. I always just expect that to work for some reason. Using a generator expression works just as well, though, and is probably clearer in the long run. Besides, I guess if `any` had a signature like def any(xs, pred=lambda x: bool(x)) or something, that would reverse the signatures of map, filter, reduce, etc. On that note, I always want the arguments of filter and reduce, but not those of map, to be reversed for some reason.
- euccastro 17y agoIf you already have a predicate function, it is not hard to say all(filter(f, items)) Composing calls like this looks cleaner than incorporating into the function interface all list manipulations that the implementor expects you to want.
- mattj 17y agoSaid before, but any(pred(x) for x in xs) is too complex?
- mccutchen 17y agoQuoting myself, now: "Using a generator expression works just as well, though, and is probably clearer in the long run." It's just that my first instinct is always to use all(xs, pred).