Skip to content

Instantly share code, notes, and snippets.

@pizycki
Created June 13, 2018 15:08
Show Gist options
  • Save pizycki/c8cee5511d4b7100f965bd33a2928021 to your computer and use it in GitHub Desktop.
Save pizycki/c8cee5511d4b7100f965bd33a2928021 to your computer and use it in GitHub Desktop.
C# Either example FP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Monacs.Core;
namespace EitherExampleExceptions
{
class Program
{
static void Main(string[] args)
{
new App().Tee(app =>
{
Enumerable.Range(1, 1000)
.Select(i => app.GetOne())
.Select(one => one.Match(left: ex => $"Error of type {ex.GetType()}.",
right: n => $"N is: {n}"))
.ToList()
.ForEach(Console.WriteLine);
});
}
}
public class App
{
Random rnd = new Random(123123214);
Processors processors = new Processors
{
(dividedBy2, n => Either.Left<Exception, string>(new Exception())),
(dividedBy3, n => Either.Left<Exception, string>(new AmbiguousMatchException())),
(dividedBy5, n => Either.Left<Exception, string>(new ArithmeticException())),
(_ => true, n => Either.Right<Exception, string>(n.ToString()))
};
public Either<Exception, string> GetOne()
{
var n = rnd.Next();
return processors.Process(n);
}
static Func<int, int, bool> dividedBy = (x, y) => x % y == 0;
static Func<int, bool> dividedBy2 = x => dividedBy(x, 2);
static Func<int, bool> dividedBy3 = x => dividedBy(x, 3);
static Func<int, bool> dividedBy5 = x => dividedBy(x, 5);
}
public static class AppExtensions
{
public static App Tee(this App app, Action<App> action)
{
action(app);
return app;
}
}
class Processors : List<(Func<int, bool>, Func<int, Either<Exception, string>>)>
{
public Either<Exception, string> Process(int n) => this.First(x => x.Item1(n)).Item2(n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment