Function pointers, Closures, and Lambda

前端 未结 12 1452
臣服心动
臣服心动 2020-11-28 01:51

I am just now learning about function pointers and, as I was reading the K&R chapter on the subject, the first thing that hit me was, \"Hey, this is kinda like a closure

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 02:39

    The closure captures the free variables in an environment. The environment will still exist, even though the surrounding code may no longer be active.

    An example in Common Lisp, where MAKE-ADDER returns a new closure.

    CL-USER 53 > (defun make-adder (start delta) (lambda () (incf start delta)))
    MAKE-ADDER
    
    CL-USER 54 > (compile *)
    MAKE-ADDER
    NIL
    NIL
    

    Using the above function:

    CL-USER 55 > (let ((adder1 (make-adder 0 10))
                       (adder2 (make-adder 17 20)))
                   (print (funcall adder1))
                   (print (funcall adder1))
                   (print (funcall adder1))
                   (print (funcall adder1))
                   (print (funcall adder2))
                   (print (funcall adder2))
                   (print (funcall adder2))
                   (print (funcall adder1))
                   (print (funcall adder1))
                   (describe adder1)
                   (describe adder2)
                   (values))
    
    10 
    20 
    30 
    40 
    37 
    57 
    77 
    50 
    60 
    # is a CLOSURE
    Function         #
    Environment      #(60 10)
    # is a CLOSURE
    Function         #
    Environment      #(77 20)
    

    Note that the DESCRIBE function shows that the function objects for both closures are the same, but the environment is different.

    Common Lisp makes both closures and pure function objects (those without an environment) both to be functions and one can call both in the same way, here using FUNCALL.

提交回复
热议问题