Revisiting Maybe monad using C# 8.0 Pattern Matching

Source Code .NET Fiddle : Maybe Monad Example C# 8.0 Pattern Matching

To be honest i didn't like the pattern matching feature the first time i show it. But i rewrote some sample functional code and i can say i might be a fan.

if you are not familiar with pattern matching read the previous article :

this article revises the Maybe monad seen previously

We will rewrite Maybe using C# 8.0 pattern matching

this is the initial

and now we can just simply replace it with

placing the map definition in the base class

public abstract class Maybe<T>
{
public Maybe<T1> Map<T1>(Func<T, T1> f) =>
this switch
{
None<T> { } => new None<T1>(),
Some<T> { Value: var v } => new Some<T1>(f(v)),
};
}

and we can use it like this :

var result = new Some<int>(4)
.Map(v => $"number is : {v}")
switch //another switch to extract the value
{
None<string> { } => "Not found",
Some<string> { Value: var v } => "some" + 5,
_ => throw new NotImplementedException(),
};

we can similarly define the Bind :

here i used extension methods but we can put that also in the base class Maybe<T>.

Practical functional C#

--

--

--

More than 14 years’ experience as full stack developer and Software Architect .https://leanpub.com/u/dimitrispapadim

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Read/Process/Write with Kafka Transactions

ICPuppies Roadmap 2022

Goibibo walks the Python 3 path

Team Collaboration with GitHub

I web-scraped “internshala.com” to compare internships in “Data Science”

Building Google Actions with Java

Secrets of a Superstar API-First Strategy — Part Two

Getting started with arduino uno for led blinking

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dimitris Papadimitriou

Dimitris Papadimitriou

More than 14 years’ experience as full stack developer and Software Architect .https://leanpub.com/u/dimitrispapadim

More from Medium

Java like Enums in C#

C# Value Types and Reference Types

Into Image

Advanced C# — SQL Server Bulk Upload

C# Razor Pages… Definitely Light-Weight.