Update the whole structure

十年热恋 提交于 2019-12-24 10:48:13

问题


Suppose I have some function which returns a struct:

(struct layer (points lines areas))

(define (build-new-layer height)
  ...
  (layer list-a list-b list-c))

I want to keep track of the last returned result something like:

(define top-side (build-new-layer 0)) ; store the first result
...
(set! top-side (build-new-layer 0.5)) ; throw away the first result and store the new one

However, for that particular code I get the error:

set!: assignment disallowed;
 cannot modify a constant
  constant: top-side

Please, tell me what would be the right way to do what I want


回答1:


What language are you using? it seems it's a matter of configuration, because in principle what you're doing should work. Go to the "choose language" window (Ctrl+L in Windows), click on "show details" and see if one of the options of the language currently in use disallows redefinition of variables. Alternatively, try using a different language.

Depending on where exactly you're going to use the stored result (I can't tell from the code in the question), you could pass it around as function parameters, in such a way that using a global variable is no longer necessary. This might be a better idea, relying on global state and mutation (the set! operation) is discouraged in Scheme.




回答2:


If you always want to keep around the last layer, then you might prefer setting the last-layer every time one is built. Like this.

(define last-layer #f)
(define build-new-layer
  (let ((save-layer #f))
    (lambda (height)
      (let ((new-layer (layer list-a ...)))
        (set! last-layer save-layer)
        (set! save-layer new-layer)
        new-layer))))

Note: if the real problem is the 'constant-ness' of last-layer then build yourself a little abstraction as:

(define-values (last-layer-get last-layer-set!)
  (begin
    (define last-layer-access
      (let ((last-layer #f))
        (lambda (type . layer)
          (case type
           ((get) last-layer)
           ((set) (set! last-layer (car layer)))))))
    (values (lambda () (last-layer-access 'get))
            (lambda (layer) (last-layer-access 'set layer))))


来源:https://stackoverflow.com/questions/15254713/update-the-whole-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!