vittorioromeo / scelta

(experimental) Syntactic sugar for variant and optional types.
https://vittorioromeo.info
MIT License
157 stars 10 forks source link

Monadic `optional` utilities #9

Closed vittorioromeo closed 6 years ago

vittorioromeo commented 6 years ago

scelta now provides various monadic operations that work on any supported optional type. Here's an example inspired by Simon Brand's "Functional exceptionless error-handling with optional and expected" article:

optional<image_view> crop_to_cat(image_view);
optional<image_view> add_bow_tie(image_view);
optional<image_view> make_eyes_sparkle(image_view);
image_view make_smaller(image_view);
image_view add_rainbow(image_view);

optional<image_view> get_cute_cat(image_view img)
{
    using namespace scelta::infix;
    return crop_to_cat(img)
         | and_then(add_bow_tie)
         | and_then(make_eyes_sparkle)
         | map(make_smaller)
         | map(add_rainbow);
}

The provided monadic optional operations can be used in two different ways:

optional<int> o{/* ... */};

// Free function syntax:
scelta::map(o, [](int x){ return x + 1; });

// Infix syntax:
o | scelta::infix::map([](int x){ return x + 1; });

These are the available operations:

The example file example/optional_cat.cpp shows usage of map and and_then using scelta::infix syntax.