Bizarre quoted list example from On Lisp -
this passage on lisp
genuinely confusing -- not clear how returning quoted list such '(oh my)
can alter how function behaves in future: won't returned list generated again in function scratch, next time called?
if define exclaim return value incorporates quoted list,
(defun exclaim (expression) (append expression ’(oh my)))
then later destructive modification of return value
(exclaim ’(lions , tigers , bears)) -> (lions , tigers , bears oh my) (nconc * ’(goodness)) -> (lions , tigers , bears oh goodness)
could alter list within function:
(exclaim ’(fixnums , bignums , floats)) -> (fixnums , bignums , floats oh goodness)
to make exclaim proof against such problems, should written:
(defun exclaim (expression) (append expression (list ’oh ’my)))
how last call exclaim
adding word goodness
result? function not referencing outside variable how did separate call nconc
alter how exclaim
function works?
a) effects of modifying literal lists undefined in common lisp standard. here see example 1 possible behavior.
(1 2 3 4)
literal list. call list
in (list 1 2 3 4)
returns freshly consed list @ runtime.
b) list literal data in code of function. every call return data object. if want provide fresh list on each call, need use list or copy-list.
c) since returned list same literal data object, modifying can have effect described. 1 imagine error happens if code , objects allocated in read-only memory. modifying list try write read-only memory.
d) 1 thing keep in mind when working literal list data in source code this: lisp compiler free optimize storage. if list happens multiple times in source code, compiler allowed detect , create 1 list. various places point 1 list. modifying list have effect, these changes visible in several places.
this may happen other literal data objects arrays/vectors.
if data structure part of code, return internal data structure, modify data structure - try modify code.
note lisp can executed interpreter. interpreter typically works on lisp source structure - code not machine code, interpreted lisp code lisp data. here might able modify source code @ runtime, not data embedded in source code.
Comments
Post a Comment