Created
December 21, 2014 15:40
-
-
Save siroky/4e42fecea11667be7e76 to your computer and use it in GitHub Desktop.
Functor 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
namespace FuncSharp | |
{ | |
public interface IFunctor<FA, FB, A, B> | |
{ | |
FB Map(FA fa, Func<A, B> f); | |
} | |
public class OptionFunctor<A, B> : IFunctor<IOption<A>, IOption<B>, A, B> | |
{ | |
public IOption<B> Map(IOption<A> fa, Func<A, B> f) | |
{ | |
return fa.Map(f); | |
} | |
} | |
public class TaskFunctor<A, B> : IFunctor<Task<A>, Task<B>, A, B> | |
{ | |
public Task<B> Map(Task<A> fa, Func<A, B> f) | |
{ | |
return fa.ContinueWith(task => f(task.Result)); | |
} | |
} | |
public class ListFunctor<A, B> : IFunctor<List<A>, List<B>, A, B> | |
{ | |
public List<B> Map(List<A> fa, Func<A, B> f) | |
{ | |
return fa.Select(f).ToList(); | |
} | |
} | |
public class FunctorTest | |
{ | |
public void Run() | |
{ | |
var o1 = 3.ToOption(); | |
var o2 = AddOne(o1, new OptionFunctor<int, int>()); | |
var t1 = Task.FromResult(3); | |
var t2 = AddOne(t1, new TaskFunctor<int, int>()); | |
var l1 = new List<int> { 1, 2, 3, 4, 5 }; | |
var l2 = AddOne(l1, new ListFunctor<int, int>()); | |
} | |
public FB AddOne<FA, FB>(FA fa, IFunctor<FA, FB, int, int> functor) | |
{ | |
return functor.Map(fa, i => i + 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment