Skip to content

Instantly share code, notes, and snippets.

@mmontone
Created July 10, 2017 00:03
Show Gist options
  • Save mmontone/40c8b51a0618aa7cf0c08ec39135fddf to your computer and use it in GitHub Desktop.
Save mmontone/40c8b51a0618aa7cf0c08ec39135fddf to your computer and use it in GitHub Desktop.
Dynamic functions
(defun make-dfun-varname (fname)
(intern (format nil "*DFUN-~A*" fname)))
(defmacro dflet (fbindings &body body)
`(let
,(loop for fbinding in fbindings
collect
(destructuring-bind (fname args &body body) fbinding
(let ((dfun-varname (make-dfun-varname fname)))
`(,dfun-varname (cons (lambda ,args
,@body)
,dfun-varname)))))
,@body))
(defmacro defdfun (name args &body body)
(let ((dfun-varname (make-dfun-varname name)))
`(progn
(defvar ,dfun-varname
(list (lambda ,args
,@body)))
(setf (symbol-function ',name)
(lambda ,args
(apply (first ,dfun-varname) (list ,@args)))))))
;; Example
#+example(progn
(defdfun dfoo ()
(print "foo1"))
(dfoo)
(defun test-dfoo ()
(dfoo))
(progn
(dfoo)
(dflet ((dfoo ()
(print "foo2")))
(test-dfoo))
(dfoo)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment