Dobiasd / FunctionalPlus

Functional Programming Library for C++. Write concise and readable C++ code.
http://www.editgym.com/fplus-api-search/
Boost Software License 1.0
2.1k stars 167 forks source link

Add monadic (fluent) interface for maybe #289

Closed tom91136 closed 9 months ago

tom91136 commented 9 months ago

This PR implements #288.

I've added new checks directly below the existing maybe tests to make sure it compiles. An extra test on chaining the fluent interface is also included, we can now do:

maybe<int> m(42);
m
  .just_if([](auto x) { return x > 0; })
  .and_then([](auto x) { return x % 2 == 0 ? just<std::string>("a") : nothing<std::string>(); })
  .lift([](auto x) { return just(x); })
  .join()
  .lift_def(nothing<std::string>(), [](auto x) { return just(x + "b"); })
  .get_with_default("c"); // == "ab"

I've made the following additions to the API:

Dobiasd commented 9 months ago

That looks splendid! Working with Maybe types is much more convenient that way. :heart_eyes:

The only potential downside of the member functions over the free functions might be the auto return type on some. However, adding an explicit return type could be quite complex with the derivation based on the passed F, etc. So let's keep it that way (with auto). In case some users don't like it because the auto-completion in their IDE does not play too well with this, they can still use the free functions (which have explicit return types). :white_check_mark:

Dobiasd commented 9 months ago

A just_if method (e.g filterM for our maybe functor) which I believe is missing.

That's a very nice addition! :rocket:

Dobiasd commented 9 months ago

Moved is_maybe from internal to top-level as we need this for join, and I also think this is a very useful API to expose.

Since we don't expose such helpers in other parts of the library, I'm not yet sure about exposing is_maybe to the fplus namespace here. .join (and .and_then) could also use is_maybe if is_maybe would still be defined in internal (at the same location in the file, i.e., above the class definition). :thinking:

tom91136 commented 9 months ago

Sure, I've reverted that part.

Dobiasd commented 9 months ago

Cool. :+1:

And, thanks a lot for this awesome contribution! :heart: