How do I globally change a variable value within function in lisp

后端 未结 3 901
迷失自我
迷失自我 2020-12-19 19:46

I would like to know if there is any way to mimic C behaviour with pointers in LISP. In C if you change a value of a variable, that pointer is pointing to, it has a global e

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 20:20

    Use a function

    If you want to use a function, you have to pass the symbol itself:

    (defun mutate (symbol value)
      (setf (symbol-value symbol) value))
    (mutate 'foo 42)
    foo
    ==> 42
    

    Note that the symbol argument to mutate is quoted.

    Use a macro

    (defmacro mutate (symbol value)
      `(setf ,symbol ,value))
    (mutate foo 42)
    foo
    ==> 42
    

    The symbol argument no longer has to be quoted.

    Discussion

    Arguments are passed by value in Lisp, which means that a function sees the value of its argument, not the place where it is stored. Thus a function invoked as (foo (! 5)), (foo 120), (foo x) sees only the number 120 and has absolutely no way of knowing whether this number is returned by a function (1st case), is a literal (2nd case) or stored in a variable (3rd case).

    Macros receive the code (the whole form) which they transform and pass the new code to the compiler (or interpreter). Thus macros can determine how to modify their arguments (called places or generalized references in that case).

提交回复
热议问题