いやまぢで。
アタマの片隅にちらっと浮かんだ断片を基に発作的にコードを書く。
今朝ちらっと浮かんだのは LISP。
発作的にマッカーシーの純LISPをマネっこ...し損ね orz
using System;
namespace Wankuma.Episteme.PureLISP {
// セル: リストとアトムの基底クラス
public abstract class Cell {
public abstract Cell CAR { get; }
public abstract List CDR { get; }
public bool ATOM { get { return this is Atom; }}
}
// リスト: とは セルとリストのペアである。
public class List : Cell {
private Cell car_;
private List cdr_;
public override Cell CAR { get { return car_; }}
public override List CDR { get { return cdr_; }}
public List(Cell car) { car_ = car; }
public List(Cell car, List cdr) { car_ = car; cdr_ = cdr; }
public override string ToString() {
return "( " + (CAR == null ? "nil" : CAR.ToString()) + " . "
+ (CDR == null ? "nil" : CDR.ToString()) + " ) ";
}
}
// アトム: はリストではない(子要素を持たない)
public class Atom : Cell {
private object atom_;
public override Cell CAR
{ get { throw new System.NotSupportedException("CAR of Atom is undefined"); }}
public override List CDR
{ get { throw new System.NotSupportedException("CDR of Atom is undefined"); }}
public Atom() { atom_ = null; }
public Atom(object atom) { atom_ = atom; }
public override string ToString() { return atom_.ToString(); }
}
// EQ と COND と DEFUN ができてねー♪
public static class LISP {
public static Cell CAR(Cell x) { return x.ATOM ? null : x.CAR; }
public static Cell CDR(Cell x) { return x.ATOM ? null : x.CDR; }
public static Cell CONS(Cell x, Cell y) {
List yy = y as List;
return new List(x, yy == null ? new List(y) : yy);
}
public static Cell QUOTE(object x) { return new Atom(x); }
public static bool NILP(Cell x) { return x == null; }
public static bool ATOM(Cell x) { return x.ATOM; }
// おためし
public static void Main() {
// ( A 123 C ) の各要素を列挙する
Cell root = CONS(QUOTE("A"),CONS(QUOTE(123),QUOTE("C")));
Console.WriteLine(root);
Console.WriteLine(CAR(root));
Console.WriteLine(CAR(CDR(root)));
Console.WriteLine(CAR(CDR(CDR(root))));
}
}
}
↓コレが実行結果。うごいてるぅ♪
( A . ( 123 . ( C . nil ) ) )
A
123
C
構想10秒実装10分。