From: Joe Richey Date: Thu, 9 Jul 2015 21:48:17 +0000 (-0700) Subject: Added default value for filter's predicate argument X-Git-Tag: v0.50.0~4 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=91343de631cbe56cb6361ea1b92f5b7cd1933a59;p=folly.git Added default value for filter's predicate argument Summary: After discussion with Tom about frozen files, we noticed that the use case of filtering out somthing that looks like false (0, nullptr, folly::none) is unnecessarily tedious. So folly::gen::filter now filters by the value of the item by default. Reviewed By: @ddrcoder Differential Revision: D2220582 --- diff --git a/folly/gen/Base-inl.h b/folly/gen/Base-inl.h index ade7b5d8..3827fdf4 100644 --- a/folly/gen/Base-inl.h +++ b/folly/gen/Base-inl.h @@ -483,7 +483,6 @@ class Map : public Operator> { } }; - /** * Filter - For filtering values from a source sequence by a predicate. * @@ -493,6 +492,13 @@ class Map : public Operator> { * | filter([](const string& str) -> bool { * return !str.empty(); * }); + * + * Note that if no predicate is provided, the values are casted to bool and + * filtered based on that. So if pointers is a vector of pointers, + * + * auto nonNull = from(pointers) | filter(); + * + * will give a vector of all the pointers != nullptr. */ template class Filter : public Operator> { diff --git a/folly/gen/Base.h b/folly/gen/Base.h index 8a52eb29..322b895e 100644 --- a/folly/gen/Base.h +++ b/folly/gen/Base.h @@ -614,8 +614,8 @@ Map field(FieldType Class::*field) { return Map(Field(field)); } -template> +template > Filter filter(Predicate pred = Predicate()) { return Filter(std::move(pred)); } diff --git a/folly/gen/test/BaseTest.cpp b/folly/gen/test/BaseTest.cpp index 62818f0d..c25f40c7 100644 --- a/folly/gen/test/BaseTest.cpp +++ b/folly/gen/test/BaseTest.cpp @@ -255,6 +255,40 @@ TEST(Gen, Filter) { EXPECT_EQ(expected, actual); } +TEST(Gen, FilterDefault) { + { + // Default filter should remove 0s + const auto expected = vector{1, 1, 2, 3}; + auto actual = + from({0, 1, 1, 0, 2, 3, 0}) + | filter() + | as(); + EXPECT_EQ(expected, actual); + } + { + // Default filter should remove nullptrs + int a = 5; + int b = 3; + int c = 0; + const auto expected = vector{&a, &b, &c}; + auto actual = + from({(int*)nullptr, &a, &b, &c, (int*)nullptr}) + | filter() + | as(); + EXPECT_EQ(expected, actual); + } + { + // Default filter on Optionals should remove folly::null + const auto expected = + vector>{Optional(5), Optional(0)}; + const auto actual = + from({Optional(5), Optional(), Optional(0)}) + | filter() + | as(); + EXPECT_EQ(expected, actual); + } +} + TEST(Gen, Contains) { { auto gen =