Function pointers, Closures, and Lambda

前端 未结 12 1423
臣服心动
臣服心动 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:34

    A lambda is an anonymous, dynamically defined function. You just cannot do that in C... as for closures (or the convination of the two), the typical lisp example would look something along the lines of:

    (defun get-counter (n-start +-number)
         "Returns a function that returns a number incremented
          by +-number every time it is called"
        (lambda () (setf n-start (+ +-number n-start))))
    

    In C terms, you could say that the lexical environment (the stack) of get-counter is being captured by the anonymous function, and modified internally as the following example shows:

    [1]> (defun get-counter (n-start +-number)
             "Returns a function that returns a number incremented
              by +-number every time it is called"
            (lambda () (setf n-start (+ +-number n-start))))
    GET-COUNTER
    [2]> (defvar x (get-counter 2 3))
    X
    [3]> (funcall x)
    5
    [4]> (funcall x)
    8
    [5]> (funcall x)
    11
    [6]> (funcall x)
    14
    [7]> (funcall x)
    17
    [8]> (funcall x)
    20
    [9]> 
    

提交回复
热议问题