Closed vittorioromeo closed 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:
scelta
optional
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:
map_or_else(o, f_def, f)
f(*o)
o
f_def()
map_or(o, def, f)
def
map(o, f)
optional{f(*o)}
and_then(o, f)
and_(o, ob)
ob
or_else(o, f)
f()
or_(o, def)
The example file example/optional_cat.cpp shows usage of map and and_then using scelta::infix syntax.
example/optional_cat.cpp
map
and_then
scelta::infix
scelta
now provides various monadic operations that work on any supportedoptional
type. Here's an example inspired by Simon Brand's "Functional exceptionless error-handling with optional and expected" article:The provided monadic
optional
operations can be used in two different ways:These are the available operations:
map_or_else(o, f_def, f)
f(*o)
ifo
is set,f_def()
otherwise.map_or(o, def, f)
f(*o)
ifo
is set,def
otherwise.map(o, f)
optional{f(*o)}
ifo
is set, an empty optional otherwise.and_then(o, f)
f(*o)
ifo
is set, an empty optional otherwise.and_(o, ob)
ob
ifo
is set, an emptyob
otherwise.or_else(o, f)
o
ifo
is set,f()
otherwise.or_(o, def)
o
ifo
is set,def
otherwise.The example file
example/optional_cat.cpp
shows usage ofmap
andand_then
usingscelta::infix
syntax.