____  ___    _  _     _   _ _____     _______
 / ___|/ _ \  | || |   | | | |_ _\ \   / / ____|
| |  _| | | | | || |_  | |_| || | \ \ / /|  _|
| |_| | |_| | |__   _| |  _  || |  \ V / | |___
 \____|\___/     |_|   |_| |_|___|  \_/  |_____|

 --- A GOPHER-LIKE INTERFACE FOR HIVE BLOCKCHAIN ---

Lets build a maybe library in C# - Maybe extensions

BY: @woz.software | CREATED: March 14, 2018, 9:37 a.m. | VOTES: 6 | PAYOUT: $0.31 | [ VOTE ]

[IMAGE: https://i.imgur.com/RApuF8I.jpg]

I thought I would add a couple of extensions to the Maybe monad to show how using monadic patterns can spread through your code when you start to use them and that is a good thing as they carry much power.

If you missed the story so far:

These new operations are extension methods. Not sure this is the correct home at the moment but until I get the repo up and running it will do :)

public static class Maybe
{
    public static IMaybe ToSome(this T value)
        => new Some(value);

    public static IMaybe ToMaybe(this T value)
        => value == null ? Maybe.None : new Some(value);

    public static IMaybe MaybeFirst(this IEnumerable enumerable)
        => enumerable.MaybeFirst(_ => true);

    public static IMaybe MaybeFirst(
        this IEnumerable enumerable, Func predicate)
        => enumerable.FirstOrDefault(predicate).ToMaybe();

    public static IMaybe MaybeFind(
        this IDictionary dictionary, TKey key)
    {
        TValue value;
        return dictionary.TryGetValue(key, out value) 
            ? value.ToMaybe() 
            : Maybe.None;
    }

    public static Func, IMaybe> Lift(
        Func function)
        => maybe => maybe.Select(function);
}

So a quick run down

So lets have some fun with these extensions.

var people = // IDictionary

var bobsCity = people
    .MaybeFind("Bob")
    .SelectMany(bob => bob.HomeAddress)
    .Select(address => address.City)
    .Recover("Unknown")
    .Value 

Here we lookup Bob by name in the storage. Bob might have a home address and if so we select the address city and if we fail at any stage we return an "Unknown" address.

Goodbye fugly TryGet semantics and not a single if in the whole block even though the lookup could fail at any stage.

The use of SelectMany is interesting, this is required because the HomeAddress is a Maybe wrapped value so this requires SelectMany to flattern the lookup. Refer back to the type signatures for Select and SelectMany and the Person object and it will be obvious.

Think and how you can use IEnumerable.SelectMany on a collection of collections to flatten it . IMaybe is really a collection that can hold 0 or 1 values so the same principle apples.

As always ask if you have any questions

Happy coding

Woz

TAGS: [ #programming ] [ #howto ] [ #tutorial ] [ #generics ] [ #monads ]

Replies

NO REPLIES FOUND.

[ BACK TO TRENDING ] [ BACK TO MENU ]
CMD>