Search code examples
functioncommon-lispredundancykeyword-argument

Most elegant/efficient way to define functions using the same variables


I defined multiple functions using some variables, that would normally be calculated in more of them. So I use keyword-arguments, that calculate the needed values by default.

Example:

(defun f (a b &key (distance (distance a b))) (c a b distance))
(defun g (a b &key (distance (distance a b))) (if (< distance (r a b))
                                                (f a b :distance distance)))
(defun h (a b &key (distance (distance a b))) (d a b distance))
(defun i (a b &key (distance (distance a b))) (g a b :distance distance)
                                              (h a b :distance distance))

Every function should be able to be called alone without specifying the keyword-arguments.

But now I also have to define the calculation of the keyword-arguments in every function.

Is there a more elegant/efficient way to do things like this? (I thought about lazy evaluation and dynamic programming)


Solution

  • You could use #=:

    (defun foo (a b &key #1=(distance (distance a b))) #|...|#)
    
    (defun bar (a b &key #1#) #|... |#)