Variable problem in lisp

I am writing a program in Common Lisp in which I need a function with this main circuit:

(defun example (initial-state modify mod-list) (loop for modification in mod-list collecting (funcall modify initial-state modification))) 

The problem is that I need the initial-state be the same every time it is passed to modify , but modify can be destructive. I would just make a copy, but I do not want to make any assumptions about which data type is initial-state .

How can i do this? Or is it possible?

Thanks!

+6
source share
1 answer

If a function can be destructive, and you can do nothing about it, then it is clear that you need to make copies of the initial-state .

One way to avoid preconfiguring the initial-state data is to leave the copy operation explicitly a problem for the caller or make it a general operation and rely on someone else to provide the method.

 ;; Version 1: the caller must provide a function that ;; returns a new fresh initial state (defun example (build-initial-state modify mod-list) (loop for modification in mod-list    collecting (funcall modify (funcall build-initial-state) modification))) ;; Version 2: copy-state is a generic function that has been ;; specialized for the state type (defun example (initial-state modify mod-list) (loop for modification in mod-list    collecting (funcall modify (copy-state initial-state) modification))) 

The first version is more general, since it allows the state to be any object, and in the second version, the copy operation depends on the type of state object (and this means that you cannot have two callers who use lists as state with different semantic semantics). However, copy-state is a general operation that you can probably use elsewhere and make the operation a universal increase in usability (instead you don't need to pass builder functions); it also allows you to enter other general operations, such as compare-state , write-state , read-state ...

+7
source

Source: https://habr.com/ru/post/890557/


All Articles