[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: replacing a function with another one

From: Michael Heerdegen
Subject: Re: replacing a function with another one
Date: Wed, 12 Mar 2014 07:11:17 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3.50 (gnu/linux)

Michael Heerdegen <address@hidden> writes:

> Because it's trivial.

I have the feeling that this might sound strange - but it's true!  So,
here is some pseudo code that shows, in a simplified manner, what
defining an around advice with `advice-add' does:

(defun my-add-around-advice (fun-to-advice advice)
  (lexical-let ((oldfun (symbol-function fun-to-advice))
                (function advice))
    (fset fun-to-advice
          (lambda (&rest r) (apply function oldfun r)))))
FUN-TO-ADVICE is the function to advice, ADVICE is the piece of advice
you want to add.  Do you recognize the line I cite all the time?  It's
what you get as resulting combined function.

Actually, it's not pseudo code but fully functional.

An example.  Let's define the faculty (a non-recursive version):

(defun my-fac (n) (reduce '* (number-sequence 1 n)))

Suppose we want to make it return the faculty of -n for negative
integers n by adding an around advice (currently it returns 1 for negative
arguments).  With the above simple implementation, you would do it
like that:

 (lambda (orig-fun n) (funcall orig-fun (abs n))))

Then, e.g.

  (my-fac -5)

    ==> 120

Of course, you can't remove the advice with my simplified version, etc.

With `advice-add' you would do

(advice-add 'my-fac :around
  (lambda (orig-fun n) (funcall orig-fun (abs n))))

Let's add another around advice that makes `my-fac' print the result in
the echo area.  This time using a named function as advice:

(defun my-fac--print-result-around-advice (orig-fun n)
  "Print result in the echo area."
  (let ((result (funcall orig-fun n)))
    (message "The faculty of %d is %d" n result)
    (sit-for 3)

(my-add-around-advice 'my-fac #'my-fac--print-result-around-advice)

These are not very useful examples, but hopefully they show a bit how it
works, and one can play with them.  You also see how to deal with
arguments and the return value of the original function.

The other advice types can be implemented similarly.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]