Skip to content

Instantly share code, notes, and snippets.

@yukihr yukihr/ycomb.el
Created May 7, 2014

Embed
What would you like to do?
Y Combinator on elisp
(require 'cl)
(defun ycomb (f)
(lexical-let ((f1 f))
(funcall
#'(lambda (x)
(lexical-let ((x1 x))
(funcall f1 (funcall x1 x1))))
#'(lambda (x)
(lexical-let ((x1 x))
(funcall f1 (funcall x1 x1))))
)))
(defun zcomb (f)
(lexical-let ((f1 f))
(funcall
#'(lambda (x)
(lexical-let ((x1 x))
#'(lambda (m)
(lexical-let ((m1 m))
(funcall (funcall f1 (funcall x1 x1)) m1)))))
#'(lambda (x)
(lexical-let ((x1 x))
#'(lambda (m)
(lexical-let ((m1 m))
(funcall (funcall f1 (funcall x1 x1)) m1)))))
)))
;; Fibonacci num of 7
(funcall
(zcomb #'(lambda (f)
(lexical-let ((f1 f))
#'(lambda (n)
(if (< n 2)
n
(+
(funcall f1 (- n 1))
(funcall f1 (- n 2))
)))))) 7)
@CestDiego

This comment has been minimized.

Copy link

CestDiego commented Oct 13, 2015

This was very good but it didn't work for a factorial. In which one has multiplication instead of addition. I did this and now it works with factorial as well:

    (defun ycomb (f)
      (lexical-let ((f1 f))
        (funcall
         #'(lambda (x)
             (lexical-let ((x1 x))
               (funcall f1 #'(lambda (y)
                               (lexical-let ((y1 y))
                                 (funcall (funcall x1 x1) y))
                               ))))
         #'(lambda (x)
             (lexical-let ((x1 x))
               (funcall f1 #'(lambda (y)
                               (lexical-let ((y1 y))
                                 (funcall (funcall x1 x1) y))))))
         )))
    (funcall
     (YCombinator #'(lambda (f)
                      (lexical-let ((f1 f))
                        #'(lambda (n)
                            (if (eq n 0)
                                1
                              (* n
                                 (funcall f1 (1- n))
                                 )))))) 7)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.