Skip to content

Instantly share code, notes, and snippets.

@tanglebones
Last active September 22, 2017 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanglebones/2640039 to your computer and use it in GitHub Desktop.
Save tanglebones/2640039 to your computer and use it in GitHub Desktop.
Type safe Cons Car Cdr in C# using only functions and allowing for different types in Cons
// cons :: a -> b -> (a -> b -> t) -> t
// cons a b = \x -> x a b
static Func<Func<TA, TB, dynamic>, dynamic> Cons<TA, TB>(TA a, TB b)
{
return f=>f(a,b);
}
// NOTE: you can not write:
// static Func<Func<TA, TB, TC>, TC> Cons<TA, TB>(TA a, TB b)
// {
// return f => f(a, b);
// }
// Because TC would be not be bound to a type at the point of defining Cons
// even tho the type of TC is not needed. What we need is a form of generic
// lambda, which can currently only be achieved by using dynamic.
// car :: ((a -> b -> a) -> t) -> t
// car x = x $ \a b -> a
static TA Car<TA, TB>(Func<Func<TA, TB, dynamic>, dynamic> f)
{
return f((a, b) => a);
}
// cdr :: ((a -> b -> b) -> t) -> t
// cdr x = x $ \a b -> b
static TB Cdr<TA, TB>(Func<Func<TA, TB, dynamic>, dynamic> f)
{
return f((a, b) => b);
}
@tanglebones
Copy link
Author

in elm:

cons a b = (\x -> x a b)
car x = x(\a b -> a)
cdr x = x(\a b -> b)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment