[Openmcl-devel] inverse function

Tobias C. Rittweiler tcr at freebits.de
Sat Feb 13 12:49:39 UTC 2010

Taoufik Dachraoui <taoufik at mazeboard.com> writes:

> Dear,
> Does someone know if there is any work done to generate an inverse of any
> given lisp function (if possible).
> Example:
>> (defun f (x)  (+ x 1))
>> (f 2)
> 3
>> (funcall (inverse #'f) 3)
> 2
>> (funcall (inverse #'f) (f 5))
> 5
> This example is very simple and serves only to describe my needs; I would
> like to use the inverse function
> for complex lisp defined functions.
> Thank you for your help

(defun inverse (f domain)
  (let ((table (make-hash-table :test #'eql)))
    (funcall domain
             #'(lambda (x)
                 (let ((y (funcall f x)))
                   (setf (gethash y table) x))))
    #'(lambda (y)
        (values (gethash y table)))))

(defun integers (from to)
  #'(lambda (fn)
      (loop for i from from to to do (funcall fn i))))

CL-USER> (defun f (x) (1+ x))

CL-USER> (defvar *f^-1* (inverse 'f (integers 0 1000)))

CL-USER> (funcall *f^-1* 3)

CL-USER> (funcall *f^-1* (f 5))


More information about the Openmcl-devel mailing list