Overview Clamps Packages CM Dictionary Clamps Dictionary Fomus
Next: The ref-object class , Previous: cl-refs , Up: cl-refs , Home: General

Clamps Packages

A short example

Let's consider a short example: A program defines two variables, v1 and v2. When changing one of these variables, the other variable doesn't change:

(defvar v1 1) ; => v1

(defvar v2 2) ; => v2

v1 ; => 1
v2 ; => 2

(setf v1 3) ; => 3

v1 ; => 3
v2 ; => 2

The program wants to ensure, that v2 is always the double value of v1. This requires that we write some mechanism that changing one of the values also changes the other value. In a very naïve way we could do it like this:

(defun set-v1 (value)
  (setf v1 value)
  (setf v2 (* 2 value))
  value)

(defun set-v2 (value)
  (setf v2 value)
  (setf v1 (/ value 2))
  value)

(set-v1 10) ; => 10

v1 ; => 10
v2 ; => 20

(set-v2 30) ; => 30

v1 ; => 15
v2 ; => 30

Although this works, there are some problems with this approach:

  • For every relation two functions need to be defined, each of them needs to get a unique name and that can become cumbersome with an increasing number of variables in the program.
  • Changing a relation requires redefining all functions which use any of the related variables.
  • Linking more than two variables makes the definitions increasingly more complex and hard to maintain.

Here is an example of an extension with a third variable v3 defining the factor of the relation of v1 and v2

(defparameter v3 2) ; => v3

(defun set-v1 (value)
  (setf v1 value)
  (setf v2 (* v3 value))
  value)

(defun set-v2 (value)
  (setf v2 value)
  (setf v1 (/ value v3))
  value)

(defun set-v3 (value)
  (setf v3 value)
  (setf v2 (* v1 value))
  v3)

(set-v3 4) ; => 4

v1 ; => 15
v2 ; => 60

(set-v2 28) ; => 28

v1 ; => 7
v2 ; => 28

Now imagine v3 is dependant on another variable v4, or there is a chain of dependencies, in the worst case even resulting in a circular dependency, when v4 is dependent on the value of v1.

Especially in a dynamic programming environment where relations between variables might frequently change during a session, the necessity of keeping track of all functions which need to be redefined and reevaluated to keep the variable state consistent becomes a major issue, making programs increasingly hard to maintain and debug.