@ysharp_design/

Hindley-Milner type inference over (Lisp-ish) S-expressio-1

C#

No description

fork
loading
Files
  • main.cs
main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
/*
    Hindley-Milner type inference ( https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system )

    over (Lisp-ish) S-expressions ( https://en.wikipedia.org/wiki/S-expression )

    Cyril Jandia (08/2016)

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

#region S-expressions ( https://en.wikipedia.org/wiki/S-expression )
public delegate object Acceptor(Token token, string match);

public class Symbol
{
    public Symbol(string id) { Id = id ?? Guid.NewGuid().ToString("P"); }
    public override string ToString() => Id;
    public string Id { get; private set; }
}

public class Token : Symbol
{
    internal Token(string id) : base(id) { }
    public Token(string pattern, Acceptor acceptor) : base(pattern) { Regex = new Regex(string.Format("^({0})", !string.IsNullOrEmpty(Pattern = pattern) ? Pattern : ".*"), RegexOptions.Compiled); ValueOf = acceptor; }
    public string Pattern { get; private set; }
    public Regex Regex { get; private set; }
    public Acceptor ValueOf { get; private set; }
}

public class SExpressionSyntax
{
    private readonly Token Space = Token("\\s+", Echo);
    private readonly Token Open = Token("\\(", Echo);
    private readonly Token Close = Token("\\)", Echo);
    private readonly Token Quote = Token("\\'", Echo);
    private Token comment;

    private static Exception Error(string message, params object[] arguments) => new Exception(string.Format(message, arguments));

    private static object Echo(Token token, string match) => new Token(token.Id);

    private static object Quoting(Token token, string match) => NewSymbol(token, match);

    private Tuple<Token, string, object> Read(ref string input)
    {
        if (!string.IsNullOrEmpty(input))
        {
            var found = null as Match;
            var sofar = input;
            var tuple = Lexicon.FirstOrDefault(current => (found = current.Item2.Regex.Match(sofar)).Success && (found.Length > 0));
            var token = tuple != null ? tuple.Item2 : null;
            var match = token != null ? found.Value : null;
            input = match != null ? input.Substring(match.Length) : input;
            return token != null ? Tuple.Create(token, match, token.ValueOf(token, match)) : null;
        }
        return null;
    }

    private Tuple<Token, string, object> Next(ref string input)
    {
        Tuple<Token, string, object> read;
        while (((read = Read(ref input)) != null) && ((read.Item1 == Comment) || (read.Item1 == Space))) ;
        return read;
    }

    public object Parse(ref string input, Tuple<Token, string, object> next)
    {
        var value = null as object;
        if (next != null)
        {
            var token = next.Item1;
            if (token == Open)
            {
                var list = new List<object>();
                while (((next = Next(ref input)) != null) && (next.Item1 != Close))
                {
                    list.Add(Parse(ref input, next));
                }
                if (next == null)
                {
                    throw Error("unexpected EOF");
                }
                value = list.ToArray();
            }
            else if (token == Quote)
            {
                var quote = next.Item3;
                next = Next(ref input);
                value = new[] { quote, Parse(ref input, next) };
            }
            else
            {
                value = next.Item3;
            }
        }
        else
        {
            throw Error("unexpected EOF");
        }
        return value;
    }

    protected Token TokenOf(Acceptor acceptor)
    {
        var found = Lexicon.FirstOrDefault(pair => pair.Item2.ValueOf == acceptor);
        var token = found != null ? found.Item2 : null;
        if ((token == null) && (acceptor != Commenting))
        {
            throw Error("missing required token definition: {0}", acceptor.Method.Name);
        }
        return token;
    }

    protected IList<Tuple<string, Token>> Lexicon { get; private set; }

    protected Token Comment { get { return comment = comment ?? TokenOf(Commenting); } }

    public static Token Token(string pattern, Acceptor acceptor) => new Token(pattern, acceptor);

    public static object Commenting(Token token, string match) => Echo(token, match);

    public static object NewSymbol(Token token, string match) => new Symbol(match);

    public static Symbol Symbol(object value) => value as Symbol;

    public static string Moniker(object value) => Symbol(value) != null ? Symbol(value).Id : null;

    public static string ToString(object value)
    {
        return
            value is object[] ?
            (
                ((object[])value).Length > 0 ?
                ((object[])value).Aggregate(new StringBuilder("("), (result, obj) => result.AppendFormat(" {0}", ToString(obj))).Append(" )").ToString()
                :
                "( )"
            )
            :
            (value != null ? (value is string ? string.Concat('"', (string)value, '"') : (value is bool ? value.ToString().ToLower() : value.ToString())).Replace("\\\r\n", "\r\n").Replace("\\\n", "\n").Replace("\\t", "\t").Replace("\\n", "\n").Replace("\\r", "\r").Replace("\\\"", "\"") : null) ?? "(null)";
    }

    public SExpressionSyntax()
    {
        Lexicon = new List<Tuple<string, Token>>();
        Include(Space, Open, Close, Quote);
    }

    public SExpressionSyntax Include(params Token[] tokens)
    {
        foreach (var token in tokens)
        {
            Lexicon.Add(new Tuple<string, Token>(token.Id, token));
        }
        return this;
    }

    public object Parse(string input)
    {
        var next = Next(ref input);
        var value = Parse(ref input, next);
        if ((next = Next(ref input)) != null)
        {
            throw Error("unexpected ", next.Item1);
        }
        return value;
    }
}
#endregion

#region Hindley-Milner type inference ( https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system )
#region Abstract syntax tree
public abstract class Node
{
    public static Const Const(object type) => new Const { Type = type };
    public static Var Var(string name) => Var(name, null);
    public static Var Var(string name, object type) => new Var { Id = name, Type = type };
    public static Apply Apply(string name, Node[] args) => Apply(name, args, null);
    public static Apply Apply(string name, Node[] args, object ctor) => new Apply { Id = name, Args = args, Type = ctor };
    public static Abstract Abstract(Node[] args, Node body) => Abstract(args, null, body);
    public static Abstract Abstract(Node[] args, object type, Node body) => new Abstract { Args = args, Body = body, Type = type };
    public static Let Let(string name, Node body) => new Let { Id = name, Body = body };
    public override string ToString() => Id;
    public abstract IType Infer(ITypeSystem system, IDictionary<string, IType> env, IList<IType> types);
    public string Id { get; set; }
    public Node[] Args { get; set; }
    public Node Body { get; set; }
    public object Type { get; set; }
}

public class Const : Node
{
    public override IType Infer(ITypeSystem system, IDictionary<string, IType> env, IList<IType> types) => !(Type is IType) ? [email protected]const(env, (string)Type) : (IType)Type;
}

public class Var : Node
{
    public override IType Infer(ITypeSystem system, IDictionary<string, IType> env, IList<IType> types)
    {
        if (!env.ContainsKey(Id))
        {
            throw new InvalidOperationException(string.Concat("undefined ", Id));
        }
        return system.Fresh(env[Id], types.ToArray());
    }
}

public class Apply : Node
{
    public override IType Infer(ITypeSystem system, IDictionary<string, IType> env, IList<IType> types)
    {
        var args = Args.Select(arg => system.Infer(env, arg, types)).ToList();
        var name = Id;
        var type = system.Infer(env, Var(name), types);
        var ctor = null as IType;
        var @out = null as IType;
        if (Type != null)
        {
            ctor = !(Type is IType) ? [email protected]const(env, (string)Type) : (IType)Type;
        }
        else
        {
            @out = system.NewGeneric();
            args.Add(@out);
        }
        system.Unify(system.NewType(ctor == null ? TypeSystem.Function : ctor, ctor == null ? TypeSystem.Function.Id : ctor.Id, args.ToArray()), type);
        return ctor == null ? @out : type;
    }
}

public class Abstract : Node
{
    public override IType Infer(ITypeSystem system, IDictionary<string, IType> env, IList<IType> types)
    {
        var known = new List<IType>(types);
        var args = new List<IType>();
        foreach (var arg in Args)
        {
            IType var;
            if (arg.Type == null)
            {
                var = system.NewGeneric();
                known.Add(var);
            }
            else
            {
                var = !(arg.Type is IType) ? [email protected]const(env, (string)arg.Type) : (IType)arg.Type;
            }
            env[arg.Id] = var;
            args.Add(var);
        }
        args.Add(system.Infer(env, Body, known));
        if (Type != null)
        {
            system.Unify(args[args.Count - 1], !(Type is IType) ? [email protected]const(env, (string)Type) : (IType)Type);
        }
        return system.NewType(TypeSystem.Function, TypeSystem.Function.Id, args.ToArray());
    }
}

public class Let : Node
{
    public override IType Infer(ITypeSystem system, IDictionary<string, IType> env, IList<IType> types)
    {
        var scope = new Dictionary<string, IType>(env);
        var known = new List<IType>(types);
        var var = system.NewGeneric();
        scope[Id] = var;
        known.Add(var);
        system.Unify(var, system.Infer(scope, Body, known));
        return env[Id] = scope[Id];
    }
}
#endregion

#region Type schemes
public interface IType
{
    IType Constructor { get; }
    string Id { get; }
    IType[] Args { get; }
    IType Self { get; }
}
#endregion

#region Type system
public interface ITypeSystem
{
    IType Fresh(IType t, IType[] types);
    IType @const(IDictionary<string, IType> env, string ctor);
    IType NewGeneric();
    IType NewType(string id);
    IType NewType(string id, IType[] args);
    IType NewType(IType constructor);
    IType NewType(IType constructor, IType[] args);
    IType NewType(IType constructor, string id);
    IType NewType(IType constructor, string id, IType[] args);
    void Unify(IType t, IType s);
    IType Infer(IDictionary<string, IType> env, Node node);
    IType Infer(IDictionary<string, IType> env, Node node, IList<IType> types);
    IType[] Infer(IDictionary<string, IType> env, Node[] nodes);
}

public class TypeSystem : ITypeSystem
{
    internal abstract class Scheme : IType
    {
        protected Scheme(string id) : this(id, null) { }
        protected Scheme(IType[] args) : this(null, args) { }
        protected Scheme(string id, IType[] args) { Id = id; Args = args ?? new IType[0]; }
        public override string ToString() => Id.ToString();
        public IType Constructor { get; protected set; }
        public virtual string Id { get; protected set; }
        public IType[] Args { get; private set; }
        public IType Self { get; internal set; }
    }

    internal class Generic : Scheme
    {
        private string Alpha() { var id = Uid; var sb = new StringBuilder(); while (id-- > 0) { var r = id % 26; var c = (char)(r + 97); sb.Insert(0, c); id = (id - r) / 26; } return sb.ToString(); }
        private string GetName() => Self != null ? Self.Id : string.Concat('`', Alpha());
        internal Generic(TypeSystem system) : base(null as string) { Uid = system.NewId(); }
        internal readonly int Uid;
        public override string ToString() => Self != null ? Self.ToString() : base.ToString();
        public override string Id { get { return GetName(); } protected set { } }
    }

    internal class Type : Scheme
    {
        internal Type(IType constructor, string id, IType[] args) : base(id, args) { Constructor = constructor ?? this; }
        public override string ToString() { return (Args.Length > 0 ? string.Format("{0}<{1}>", Id, string.Concat(string.Join(", ", Args.Take(Args.Length - 1).Select(arg => arg.ToString())), (Args.Length > 1 ? ", " : string.Empty), Args[Args.Length - 1].ToString())) : base.ToString()); }
    }

    private static IType Create(string id) => Create(null, id);
    private static IType Create(IType constructor, string id) => Create(constructor, id, null);
    private static IType Create(IType constructor, string id, IType[] args) => new Type(constructor, id, args);

    private static IType Prune(IType t)
    {
        Generic var = t as Generic;
        return (var != null) && (var.Self != null) ? (var.Self = Prune(var.Self)) : t;
    }

    private static bool OccursIn(IType t, IType s) => ((s = Prune(s)) != t) ? (s is Type ? OccursIn(t, s.Args) : false) : true;
    private static bool OccursIn(IType t, IType[] types) => types.Any(type => OccursIn(t, type));

    private IType Fresh(IType t, IType[] types, IDictionary<int, IType> vars)
    {
        vars = vars ?? new Dictionary<int, IType>();
        t = Prune(t);
        var var = t as Generic;
        var type = t as Type;
        if (var != null)
        {
            if (!OccursIn(t, types))
            {
                if (!vars.ContainsKey(var.Uid))
                {
                    vars[var.Uid] = NewGeneric();
                }
                return vars[var.Uid];
            }
            else
            {
                return t;
            }
        }
        else if (type != null)
        {
            return NewType(type.Constructor, type.Id, type.Args.Select(arg => Fresh(arg, types, vars)).ToArray());
        }
        else
        {
            throw new InvalidOperationException(string.Concat("unsupported: ", t.GetType()));
        }
    }

    private int id;

    internal int NewId() => ++id;

    public static readonly IType Function = Create("Function");

    public static readonly ITypeSystem Default = Create();

    public static ITypeSystem Create() => new TypeSystem();

    public static ITypeSystem Create<TSystem>() where TSystem : ITypeSystem, new() => new TSystem();

    #region ITypeSystem
    public IType Fresh(IType t, IType[] types) => Fresh(t, types, null);

    public IType @const(IDictionary<string, IType> env, string ctor)
    {
        if (!env.ContainsKey(ctor))
        {
            throw new InvalidOperationException(string.Concat("unknown: ", ctor));
        }
        return env[ctor];
    }

    public IType NewGeneric() => new Generic(this);

    public IType NewType(string id) => NewType(id, null);
    public IType NewType(string id, IType[] args) => NewType(null, id, args);
    public IType NewType(IType constructor) => NewType(constructor, null as IType[]);
    public IType NewType(IType constructor, IType[] args) => NewType(constructor, constructor.Id, args);
    public IType NewType(IType constructor, string id) => NewType(constructor, id, null);
    public IType NewType(IType constructor, string id, IType[] args) => Create(constructor, id, args);

    public void Unify(IType t, IType s)
    {
        t = Prune(t);
        s = Prune(s);
        if (t is Generic)
        {
            if (t != s)
            {
                if (OccursIn(t, s))
                {
                    throw new InvalidOperationException("recursive unification");
                }
                ((Generic)t).Self = s;
            }
        }
        else if ((t is Type) && (s is Generic))
        {
            Unify(s, t);
        }
        else if ((t is Type) && (s is Type))
        {
            var t_type = (Type)t;
            var s_type = (Type)s;
            if ((t_type.Constructor.Id != s_type.Constructor.Id) || (t_type.Args.Length != s_type.Args.Length))
            {
                throw new InvalidOperationException(string.Concat(t_type, " incompatible with ", s_type));
            }
            for (var i = 0; i < t_type.Args.Length; i++)
            {
                Unify(t_type.Args[i], s_type.Args[i]);
            }
        }
        else
        {
            throw new InvalidOperationException("undecided unification");
        }
    }

    public IType Infer(IDictionary<string, IType> env, Node node) => Infer(env, node, null);

    public IType Infer(IDictionary<string, IType> env, Node node, IList<IType> types) => node.Infer(this, env, types ?? new List<IType>());

    public IType[] Infer(IDictionary<string, IType> env, Node[] nodes) => nodes.Select(node => Infer(env, node)).ToArray();
    #endregion
}
#endregion
#endregion

#region Alright...
class MainClass {
  public static void Main (string[] args) {
        var syntax =
            new SExpressionSyntax().
            Include
            (
                // Not-quite-Lisp-indeed; just tolen from our host, C#, as-is
                SExpressionSyntax.Token("\\/\\/.*", SExpressionSyntax.Commenting),
                SExpressionSyntax.Token("false", (token, match) => false),
                SExpressionSyntax.Token("true", (token, match) => true),
                SExpressionSyntax.Token("null", (token, match) => null),

                // Integers (unsigned)
                SExpressionSyntax.Token("[0-9]+", (token, match) => int.Parse(match)),

                // String literals
                SExpressionSyntax.Token("\\\"(\\\\\\n|\\\\t|\\\\n|\\\\r|\\\\\\\"|[^\\\"])*\\\"", (token, match) => match.Substring(1, match.Length - 2)),

                // For identifiers...
                SExpressionSyntax.Token("[\\$_A-Za-z][\\$_0-9A-Za-z\\-]*", SExpressionSyntax.NewSymbol),

                // ... and such
                SExpressionSyntax.Token("[\\!\\&\\|\\<\\=\\>\\+\\-\\*\\/\\%\\:]+", SExpressionSyntax.NewSymbol)
            );

        var system = TypeSystem.Default;
        var env = new Dictionary<string, IType>();

        // Classic
        var @bool = system.NewType(typeof(bool).Name);
        var @int = system.NewType(typeof(int).Name);
        var @string = system.NewType(typeof(string).Name);

        // Generic list of some `item' type : List<item>
        var ItemType = system.NewGeneric();
        var ListType = system.NewType("List", new[] { ItemType });

        // Populate the top level typing environment
        env[@bool.Id] = @bool;
        env[@int.Id] = @int;
        env[@string.Id] = @string;
        env[ListType.Id] = env["nil"] = ListType;

        // Bake some operator function types (to have something to infer about, in familiar-looking arith. expressions)
        var binary = system.NewGeneric();
        system.Infer(env, Node.Let("+", Node.Abstract(new[] { Node.Var("left", binary), Node.Var("right", binary) }, binary, Node.Var("left"))));
        system.Infer(env, Node.Let("-", Node.Abstract(new[] { Node.Var("left", binary), Node.Var("right", binary) }, binary, Node.Var("left"))));
        system.Infer(env, Node.Let("*", Node.Abstract(new[] { Node.Var("left", binary), Node.Var("right", binary) }, binary, Node.Var("left"))));
        system.Infer(env, Node.Let("/", Node.Abstract(new[] { Node.Var("left", binary), Node.Var("right", binary) }, binary, Node.Var("left"))));
        system.Infer(env, Node.Let("<", Node.Abstract(new[] { Node.Var("left", binary), Node.Var("right", binary) }, @bool, Node.Const(@bool))));
        system.Infer(env, Node.Let(">", Node.Abstract(new[] { Node.Var("left", binary), Node.Var("right", binary) }, @bool, Node.Const(@bool))));

        // A ternary if-then-else will come in handy too
        var ifThenElse = system.NewGeneric();
        system.Infer(env, Node.Let("if", Node.Abstract(new[] { Node.Var("condition", @bool), Node.Var("then", ifThenElse), Node.Var("else", ifThenElse) }, ifThenElse, Node.Var("then"))));

		// And List ops, too
        system.Infer(env, Node.Let(":", Node.Abstract(new[] { Node.Var("item", ItemType), Node.Var("list", ListType) }, ListType, Node.Const(ListType))));
        system.Infer(env, Node.Let("empty", Node.Abstract(new[] { Node.Var("list", ListType) }, @bool, Node.Const(@bool))));
        system.Infer(env, Node.Let("head", Node.Abstract(new[] { Node.Var("list", ListType) }, ItemType, Node.Const(ItemType))));
        system.Infer(env, Node.Let("tail", Node.Abstract(new[] { Node.Var("list", ListType) }, ListType, Node.Const(ListType))));
            
        // DRY helpers
        var isFunction = null as Func<IType, bool>;
        isFunction = type => type != null ? (type.Constructor != null ? type.Constructor.Id == TypeSystem.Function.Id : isFunction(type.Self)) : false;
        Func<object, bool> isArray = value => value is object[];
        Func<object, object[]> array = value => (object[])value;

        // A kind of poor man's visitor (over the S-expr) : just a bunch of lambdas
        Func<object, object> visitSExpr = null;
        Func<object, object> visitLet = null;
        Func<object, Node> visitDefine = null;
        Func<object, Node> visitApply = null;
        Func<object, Node> visitLambda = null;
        Func<object, Node> visitConst = null;
        Func<object, Node> visitVar = null;
        visitSExpr =
            sexpr =>
                isArray(sexpr) ?
                (
                    array(sexpr).Length > 1 ?
                    (
                        (SExpressionSyntax.Symbol(array(sexpr)[0]) == null) || (SExpressionSyntax.Moniker(array(sexpr)[0]) != "let") ?
                        (
                            (SExpressionSyntax.Symbol(array(sexpr)[1]) == null) || (SExpressionSyntax.Moniker(array(sexpr)[1]) != "=>") ?
                            visitApply(sexpr)
                            :
                            visitLambda(sexpr)
                        )
                        :
                        visitLet(sexpr)
                    )
                    :
                    array(sexpr).Length > 0 ? visitSExpr(array(sexpr)[0]) : null
                )
                :
                SExpressionSyntax.Symbol(sexpr) != null ? visitVar(sexpr) : visitConst(sexpr);
        visitLet =
            let =>
                array(array(let)[1]).Select(define => visitDefine(define)).ToArray();
        visitDefine =
            define =>
                Node.Let(SExpressionSyntax.Moniker(array(define)[0]), (Node)visitSExpr(array(define)[1]));
        visitApply =
            apply =>
                Node.Apply
                (
                    SExpressionSyntax.Moniker(array(apply)[0]),
                    array(apply).Skip(1).Select(arg => visitSExpr(arg)).Cast<Node>().ToArray(),
                    !env.ContainsKey((string)(apply = SExpressionSyntax.Moniker(array(apply)[0]))) ||
                    !isFunction(env[(string)apply])
                    ?
                    (
                        env.ContainsKey((string)apply) ?
                        (
                            !isFunction(env[(string)apply]) ?
                            env[(string)apply]
                            :
                            null
                        )
                        :
                        null
                    )
                    :
                    null
                );
        visitLambda =
            lambda =>
                Node.Abstract
                (
                    array(array(lambda)[0]).Select(arg => visitVar(arg)).ToArray(),
                    (Node)visitSExpr(array(lambda)[2])
                );
        visitConst =
            @const =>
                Node.Const(@const.GetType().Name);
        visitVar =
            var =>
                Node.Var(SExpressionSyntax.Moniker(var));

        Action<object> analyze =
            (ast) =>
            {
                var nodes = (Node[])visitSExpr(ast);
                foreach (var node in nodes)
                {
                    try
                    {
                        Console.WriteLine();
                        Console.WriteLine("{0} : {1}", node.Id, system.Infer(env, node));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                Console.WriteLine();
                Console.WriteLine("... Done.");
            };

        // Parse some S-expr (in string representation)
        var source =
            syntax.
            Parse
            (@"
                (
                    let
                    (
                    	// Type inference ""playground""

						// Classic..                    	
                        ( id ( ( x ) => x ) ) // identity
                        
                        ( o ( ( f g ) => ( ( x ) => ( f ( g x ) ) ) ) ) // composition
                        
                        ( factorial ( ( n ) => ( if ( > n 0 ) ( * n ( factorial ( - n 1 ) ) ) 1 ) ) )
                        
                        // More interesting..
                        ( fmap (
                            ( f l ) =>
                            ( if ( empty l )
                                ( : ( f ( head l ) ) ( fmap f ( tail l ) ) )
                                nil
                            )
                        ) )
                        
                        // your own...
                    )
                    ( )
                )
            ");

        // Visit the parsed S-expr, turn it into a more friendly AST for H-M
        // (see Node, et al, above) and infer some types from the latter
        analyze(source);
  }
}
#endregion