Skip to content

Instantly share code, notes, and snippets.

@markomanninen
Last active October 27, 2017 18:04
Show Gist options
  • Save markomanninen/d0549e1ea5dd052b48487f9cc2add69e to your computer and use it in GitHub Desktop.
Save markomanninen/d0549e1ea5dd052b48487f9cc2add69e to your computer and use it in GitHub Desktop.
Lambda Calculus Interpreter
(eval-and-compile(defmacro D[&rest e]`(defn ~@e))(D €[a b](.extend a b)a)(D §[a](.reverse a)a)(D ¤[a](first a))(D ?[e](instance? F e))(D £[e](if(coll? e)(if(?(¤ e))(£(apply(¤ e)(rest e)))(if(? e)e(do(def x(list(map £ e)))(if(?(¤ x))(£ x)x))))e))(D $[a b c](if(coll? c)(if(? c)(if(=(¤ c)a)c(F[(¤ c)($ a b(second c))]))((type c)(genexpr($ a b d)[d c])))(if(= a c)b c)))(defclass V[HySymbol](D --call--[self &rest v](€[self]v)))(defclass F[HyExpression](D --call--[self a &rest b](def e(£($(¤ self)a(second self))))(if b(def e(apply e b)))e)))(defmacro L[&rest e](reduce(fn[y x]`((fn[](def ~x(V(gensym'~x)))(F[~x ~y]))))(§(list e))))
@markomanninen
Copy link
Author

markomanninen commented Oct 27, 2017

Lambda calculus interpreter in Hy, 630 chars (648 bytes) minified. Supports multiary argument notation and multiple parameter passing. No need for dot because the last element of the function is taken as the body of the function.

Calculating the fourth triangular number by Lambda calculus using ycombinator:

; int to church number generator
(defmacro NUM [n &rest args]
  `(L x y ~(reduce (fn [x y] (hy.HyExpression ['x x])) (range n) 'y) ~@args))

; reverse church number to int
(defn MUN [n]
  (def x (n 1 0))
  (if (numeric? x) x
    (sum (flatten x))))

; lambda forms
(def COND (L a b c (a b c))
     TRUE (L a b a)
     FALSE (L a b b)
     ZERO? (L s (s (L a FALSE) TRUE))
     SUM (L m n x y (m x (n x y)))
     IDENT (L x x)
     PRED (L n x y (n (L g h (h (g x))) (L x y) IDENT))
     SELF (L f x (f f x))
    ; note the usage of coll body to prevent too early evaluation of the ycombinator
     YCOMB (L f [(L x (x x)) (L x (f (x x)))])
)

(MUN (YCOMB (L f n (COND (ZERO? n) n (SUM n (f (PRED n))))) (NUM 4)))

should yield: 10

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