Created
April 30, 2012 13:12
-
-
Save dtchepak/2558247 to your computer and use it in GitHub Desktop.
Attempt at C# Functors
This file contains hidden or 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
public static class Functors | |
{ | |
public static IEnumerable<B> fmap<A,B>(this IEnumerable<A> functor, Func<A, B> f) | |
{ | |
return functor.Select(f); | |
} | |
public static B? fmap<A, B>(this A? functor, Func<A, B> f) where A : struct where B : struct | |
{ | |
return functor == null ? null : (B?) f(functor.Value); | |
} | |
} | |
public class FunctorTests { | |
[Test] | |
public void Fmap_over_collection() | |
{ | |
var collection = new[] { 1, 2, 3 }; | |
var result = collection.fmap(x => x+1); | |
Assert.That(result, Is.EqualTo(new[] {2,3,4})); | |
} | |
[Test] | |
public void Fmap_over_nullable() | |
{ | |
int? justValue = 2; | |
int? nothing = null; | |
Assert.That(justValue.fmap(x => x + 1), Is.EqualTo(3)); | |
Assert.That(nothing.fmap(x => x + 1), Is.Null); | |
} | |
[Test] | |
public void Fmap_over_string() | |
{ | |
Assert.That("hello".fmap(Char.ToUpper), Is.EqualTo("HELLO")); | |
} | |
[Test] | |
public void Fmap_converting_collection_to_different_type() | |
{ | |
var collection = new[] { 1, 2, 3 }; | |
Assert.That(collection.fmap(x => x.ToString()), Is.EqualTo(new[] { "1", "2", "3" })); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment