Created
July 21, 2022 08:57
-
-
Save mirmostafa/132eaea9fc306022dc9d374ac5ecfcf4 to your computer and use it in GitHub Desktop.
Simple Monad Design Pattern in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Monad<TValue> | |
{ | |
private readonly TValue? _value; | |
public Monad(TValue? value) | |
=> this._value = value; | |
public Monad<TResult?> AnyWay<TResult>(in Func<TValue?, TResult?> func) | |
=> new(func(this._value)); | |
public Monad<TValue?> AnyWay(in Action<TValue?> func) | |
{ | |
func(this._value); | |
return this; | |
} | |
public Monad<TResult?> NotNull<TResult>(in Func<TValue, TResult?> func) | |
=> this._value is not null ? new(func(this._value)) : new(default); | |
public Monad<TValue?> NotNull(in Action<TValue> func) | |
{ | |
if (this._value is not null) | |
{ | |
func(this._value); | |
} | |
return this; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var p = new Person("Ali", 5); | |
var maybe = new Monad<Person>(p) | |
.NotNull(p => new Person("Reza", 5)) | |
.AnyWay(p => WriteLine($"p: {p}")) | |
.NotNull(_ => (Person?)null) | |
.AnyWay(p => WriteLine($"p: {p}")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment