Skip to content

Instantly share code, notes, and snippets.

@jammy-dodgers
Last active June 24, 2020 11:23
Show Gist options
  • Save jammy-dodgers/cb200254c096b4a30fe10902fdeeff6c to your computer and use it in GitHub Desktop.
Save jammy-dodgers/cb200254c096b4a30fe10902fdeeff6c to your computer and use it in GitHub Desktop.
C# is a dynamically typed programming language
using System;
//https://aphyr.com/posts/340-reversing-the-technical-interview
namespace jambox
{
class Program
{
delegate dynamic V(dynamic d);
static V cons(dynamic lhs, dynamic rhs) => (b) => b ? lhs : rhs;
static dynamic nth(dynamic l, dynamic n) => n == 0 ? l(true) : nth(l(false), n-1);
static dynamic reverse(dynamic l, dynamic rest = null) =>
l(false) == null ? cons(l(true), rest) : reverse(l(false), cons(l(true), rest));
static dynamic map(dynamic l, V fn) =>
l == null ? null : cons(fn(l(true)), map(l(false), fn));
static int len(dynamic l, dynamic i = null) => l == null ? i ?? 0 : len(l(false), i == null ? 1 : i+1);
static void pretty_print(dynamic l) {
var tlen = len(l);
var i = 0;
Console.Write("(");
map(l, (V)((n) => {
Console.Write($"{n}{(++i==tlen?"":", ")}");
return 0;
}));
Console.WriteLine(")");
}
static void Main(string[] args)
{
var v = cons(1, cons(2, cons(3, null)));
pretty_print(v);
Console.WriteLine(nth(v, 2));
pretty_print(reverse(v));
Console.WriteLine(v);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment