Last active
November 15, 2023 18:09
-
-
Save cute-jumper/efe2c978b8df7379ea255db31d12b534 to your computer and use it in GitHub Desktop.
Y Combinator in Emacs Lisp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Based on https://rosettacode.org/wiki/Y_combinator#Common_Lisp | |
;; Y combinator in Emacs Lisp | |
(require 'cl-lib) | |
(defun Y (f) | |
((lambda (x) (funcall x x)) | |
(lambda (y) (funcall f (lambda (&rest args) | |
(apply (funcall y y) args)))))) | |
(defun fac (f) | |
(lambda (n) | |
(if (zerop n) | |
1 | |
(* n (funcall f (1- n)))))) | |
(defun fib (f) | |
(lambda (n) | |
(cl-case n | |
(0 0) | |
(1 1) | |
(otherwise (+ (funcall f (- n 1)) | |
(funcall f (- n 2))))))) | |
(funcall (Y 'fac) 10) ; => 3628800 | |
(funcall (Y 'fib) 10) ; => 55 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, I think this implementation of
Y
can be made slightly simpler yet. Here's my take:Lexical binding needs to be enabled for that to work, otherwise Emacs will complain about the value of
proc
(dynamic scope can be confusing). Below are two test scenarios: head- and tail-recursive implementations of factorial: