Recommendation: Maybe<T>.IfNone()
See original GitHub issueMaybe<T>.UnWrap()and Maybe<T>.Match are great if you want to leave the monad and operate on values, but a lot of the benefits of the monad come with the fluent chaining of operations and transformations.
Often, as a Maybe<T> is working its way through layers of an application, there comes a point at which a default/fallback value is known and can be provided to the Maybe<T> but I don’t what to unwrap it.
Example:
Maybe<string> firstName = "sean";
Maybe<string> lastName = "wright";
// How do I supply a fallback value (in the case of `Maybe<string>.None` without unwrapping, like "unknown"?
Maybe<string> fullName = firstName.Bind(f => lastName.Map(l => $"{f} {l}"));
// later on ...
// if `fullName` was empty earlier I'd like it to have had the value "unknown" so that `uniqueFullName`
// wouldn't be just a Guid
Maybe<string> uniqueFullName = fullName.Map(n => $"{n}{Guid.NewGuid()}");
I propose something like IfNone():
public static Maybe<T> IfNone<T>(this Maybe<T> source, T fallback)
{
if (source.HasNoValue)
{
return fallback;
}
return source;
}
Or maybe it would make sense to add an overload to Maybe<T>.Map() that took a 2nd parameter of a fallback value?
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (5 by maintainers)
Top Results From Across the Web
Cheatsheet: Option (in Rust) vs Maybe (in Haskell) - IV Notes
They are recommended when you have a function call returning default value. In Haskell there is no need for this, since it is...
Read more >Functions, operators, and conditionals | BigQuery
This topic is a compilation of functions, operators, and conditional expressions. To learn more about how to call functions, function call rules, the...
Read more >Built-in template tags and filters
This document describes Django's built-in template tags and filters. It is recommended that you use the automatic documentation, if available, as this will...
Read more >Null in Python: Understanding Python's NoneType Object
In this tutorial, you'll learn about the NoneType object None, which acts as the null in Python. This object represents emptiness, and you...
Read more >bond::maybe< T, typename boost::disable_if< detail:: ...
If this instance contains nothing, construct a default instance of T; otherwise, preserve the existing value. Returns: A reference to the value. ◇...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Ok, I’ll make a PR for this!
I’m guessing we’ll want the full suite of extension overloads including additions to
AsyncMaybeExtensions.cs?Preferrably, yes.