Search code examples
memorylispstructurecommon-lisp

returning mutated structures efficiently


I have a structure:

(defstruct spider omegas values continuation)

and I have functions that take in this structure and return a mutated version of it:

(defun dec (s)
  (make-spider
    :omegas (spider-omegas s)
    :values (cons (- (car (spider-values s)) 1) (cdr (spider-values s)))
    :continuation (cdr (spider-continuation s))))

And I have a hunch that this is creating new instances of spider in memory that don't need to be there (google has been no help). I care that what I'm returning is its own block of memory but I don't care about the spider that is the argument s by the time I'm done with the function. Is there a smoother way to return structures like this?


Solution

  • If you just want to mutate the argument structure object:

    (defun dec (s)
      (decf (first (spider-values s)))  ; mutates the list of values
      (pop (spider-continuation s))
      s)