Skip to content

Instantly share code, notes, and snippets.

View ythirion's full-sized avatar

Yoan Thirion ythirion

View GitHub Profile
@ythirion
ythirion / either.cs
Created December 18, 2019 15:36
Either
public static Either<Exception, string> GetHtml(string url)
{
var httpClient = new HttpClient(new HttpClientHandler());
try
{
var httpResponseMessage = httpClient.GetAsync(url).Result;
return httpResponseMessage.Content.ReadAsStringAsync().Result;
}
catch (Exception ex) { return ex; }
}
@ythirion
ythirion / memoization.cs
Created December 18, 2019 15:29
memoization
static Func<string, string> GenerateGuidForUser = user => user + ":" + Guid.NewGuid();
static Func<string, string> GenerateGuidForUserMemoized = memo(GenerateGuidForUser);
[Fact]
public void memoization_example()
{
GenerateGuidForUserMemoized("spongebob");// spongebob:e431b439-3397-4016-8d2e-e4629e51bf62
GenerateGuidForUserMemoized("buzz");// buzz:50c4ee49-7d74-472c-acc8-fd0f593fccfe
GenerateGuidForUserMemoized("spongebob");// spongebob:e431b439-3397-4016-8d2e-e4629e51bf62
}
@ythirion
ythirion / bind.cs
Created December 18, 2019 15:28
Bind
static Option<double> Half(double x)
=> x % 2 == 0 ? x / 2 : Option<double>.None;
[Fact]
public void bind_monad()
{
Option<double>.Some(3).Bind(x => Half(x));// None
Option<double>.Some(4).Bind(x => Half(x));// Some(2)
}
@ythirion
ythirion / func_composition.cs
Created December 18, 2019 15:22
function composition
static Func<int, int> Add2 = x => x + 2;
static Func<int, int> Add3 = x => x + 3;
static int Add5(int x) => Add2.Compose(Add3)(x);
@ythirion
ythirion / list_functors.cs
Created December 18, 2019 15:20
Lists are functors
new int[] { 2, 4, 6 }.Map(x => x + 3); // 5,7,9
new List<int> { 2, 4, 6 }.Map(x => x + 3); // 5,7,9
//Prefer use List (Immutable list)
List(2, 4, 6).Map(x => x + 3); // 5,7,9
@ythirion
ythirion / Option.cs
Created December 18, 2019 15:13
Option monad
Option<int> aValue = 2;
aValue.Map(x => x + 3); // Some(5)
Option<int> none = None;
none.Map(x => x + 3); // None
//Left -> Some, Right -> None
aValue.Match(x => x + 3, () => 0); // 5
none.Match(x => x + 3, () => 0); // 0
@ythirion
ythirion / recordTypes.cs
Created December 18, 2019 15:04
Immutable Record types
public class User
{
public readonly Guid Id;
public readonly string Name;
public readonly int Age;
public User(Guid id, string name, int age)
{
Id = id;
Name = name;
@ythirion
ythirion / pure.cs
Created December 18, 2019 13:55
Pure function
static int Double(int i) => i * 2;