Skip to content

Instantly share code, notes, and snippets.

@paavohuhtala
Created November 14, 2016 10:44
Show Gist options
  • Save paavohuhtala/78f939c7acb29bd685d22e42fbeafd07 to your computer and use it in GitHub Desktop.
Save paavohuhtala/78f939c7acb29bd685d22e42fbeafd07 to your computer and use it in GitHub Desktop.
Trying out the typeclass encoding proposed in Classes for the masses
using System;
using System.Linq;
using System.Collections.Generic;
namespace ClassesForTheMasses
{
public interface Zero<A> { A Zero(); }
public interface One<A> { A One(); }
public interface Add<A> { A Add(A x, A y); }
public interface From<A, TFrom> { A From(TFrom x); }
public interface Num<A> : Zero<A>, One<A>, Add<A>, From<A, int> {};
public struct NumInt : Num<int> {
public int Zero() => 0;
public int One() => 1;
public int Add(int x, int y) => x + y;
public int From(int x) => x;
}
public struct NumLong : Num<long> {
public long Zero() => 0;
public long One() => 1;
public long Add(long x, long y) => x + y;
public long From(int x) => x;
}
public struct NumDouble : Num<double> {
public double Zero() => 0;
public double One() => 1;
public double Add(double x, double y) => x + y;
public double From(int x) => x;
}
public static class GenericMath {
public static IEnumerable<T> Fib<T, TNum>() where TNum : struct, Num<T> {
var num = default(TNum);
var prev_1 = num.One();
var prev_2 = num.One();
yield return prev_1;
yield return prev_2;
while (true) {
var next = num.Add(prev_1, prev_2);
yield return next;
prev_2 = prev_1;
prev_1 = next;
}
}
}
public class Program
{
public static void Main(string[] args)
{
var fibs = GenericMath.Fib<int, NumInt>().Take(25).ToList();
Console.WriteLine("[{0}]", String.Join(", ", fibs));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment