Created
June 29, 2020 11:45
-
-
Save CraftyFella/251549e7a6b98e34711080b3ff0a64fb to your computer and use it in GitHub Desktop.
Map and Bind in csharp with Option.
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
using System; | |
namespace ConsoleApp1 | |
{ | |
public class Option<T> | |
{ | |
private bool hasValue; | |
private T value; | |
private Option(T value) | |
{ | |
this.value = value; | |
this.hasValue = true; | |
} | |
private Option() | |
{ | |
this.hasValue = false; | |
} | |
public bool HasValue => hasValue; | |
public T Value | |
{ | |
get | |
{ | |
if (!hasValue) | |
{ | |
throw new Exception("bad times"); | |
} | |
return value; | |
} | |
} | |
public static Option<T> Some(T value) | |
{ | |
return new Option<T>(value); | |
} | |
public static Option<T> None = new Option<T>(); | |
public override string ToString() | |
{ | |
return hasValue ? $"Some({this.value})" : $"None"; | |
} | |
} | |
public static class OptionEx | |
{ | |
public static Option<TTo> Map<TFrom, TTo>(this Option<TFrom> from, Func<TFrom, TTo> map) | |
{ | |
if (from.HasValue) | |
{ | |
return Option<TTo>.Some(map.Invoke(@from.Value)); | |
} | |
return Option<TTo>.None; | |
} | |
public static Option<TTo> Bind<TFrom, TTo>(this Option<TFrom> from, Func<TFrom, Option<TTo>> map) | |
{ | |
if (from.HasValue) | |
{ | |
return map.Invoke(@from.Value); | |
} | |
return Option<TTo>.None; | |
} | |
} | |
class Calc | |
{ | |
public static Func<int, int> Add(int a) | |
{ | |
return b => a + b; | |
} | |
public static Func<int, Option<int>> Divide(int a) | |
{ | |
return b => | |
{ | |
try | |
{ | |
return Option<int>.Some(b / a); | |
} | |
catch (Exception ex) | |
{ | |
return Option<int>.None; | |
} | |
}; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var value = Option<int>.Some(5); | |
var result = value.Map(Calc.Add(5)); | |
Console.WriteLine($"{result}"); | |
var result2 = value.Bind(Calc.Divide(5)); | |
Console.WriteLine($"{result2}"); | |
var result3 = value.Map(Calc.Add(1)).Map(Calc.Add(1)); | |
Console.WriteLine($"{result3}"); | |
var result4 = value.Map(Calc.Add(1)).Map(Calc.Add(1)).Bind(Calc.Divide(0)); | |
Console.WriteLine($"{result4}"); | |
var result5 = value.Bind(Calc.Divide(0)).Map(Calc.Add(1)); | |
Console.WriteLine($"{result5}"); | |
var result6 = value.Map(Calc.Divide(5)); | |
Console.WriteLine($"{result6}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment