Hacker News new | ask | show | jobs
by BoingBoomTschak 9 days ago
Huh, I guess I "knew" since keywords are just regular symbols in the KEYWORD package in this situation, but it never occurred to me to do something that cursed. Very cool!

But this made me realize there's no way in CL (even with PROGV shenanigans) to temporarily bind the function value of a symbol, unlike the variable one through a simple LET =(

So this turns in this horrible (and incorrect, since this doesn't restore the previous FDEFINITIONs) thing when you want to use this hack "properly":

  (defun calculate (instructions)
    (setf (symbol-function :add)      #'+
          (symbol-function :subtract) #'-
          (symbol-function :multiply) #'*)
    (unwind-protect
         (reduce
          (lambda (result op-value)
            (funcall (car op-value) result (cadr op-value)))
          instructions
          :initial-value 0)
      (fmakunbound :add)
      (fmakunbound :subtract)
      (fmakunbound :multiply)))
1 comments

There are no dynamically scoped function bindings in Common Lisp.

Pascal Costanza somehow implemented such a thing. See 2003 paper "Dynamically Scoped Functions as the Essence of AOP", a precursor to work on AspectL and ContextL.

https://dl.acm.org/doi/pdf/10.1145/944579.944587

Dynamically scoped functions are wrappers which indirect to lambdas bound to a special variable; i.e. this is boostrapped out of dynamic variable scope.