开发者

Identifiers and Binding in Scheme - how to interpret the function?

I am reading DrRacket document http://docs.racket-lang.org/guide/binding.html

There is a function

  (define f
    (lambda (append)
      (define cons (append "ugly" "confusing"))
      (let ([append 'this-w开发者_如何学Pythonas])
        (list append cons))))
  > (f list)
  '(this-was ("ugly" "confusing"))

I see that we define function f, inside we define lambda that takes (append), why ? Procedure (body) for lambda is another function called cons, that appends two strings.

I don't understand this function at all. Thanks !


The section that you're referring to demonstrates lexical scope in Racket. As in other Scheme implementations, the main point is that you can "shadow" every binding in the language. Unlike most "mainstream" languages, there are no real keywords that are "sacred" in the sense that they can never be shadowed by a local binding.

Note that a really good tool to visualize what is bound where is DrRacket's "check syntax" button: click it, and you'll see your code with highlights that shows which parts are bindings, which are special forms -- and if you hover the mouse over a specific name, you'll see an arrow that tells you where it came from.


Scheme takes some getting used to :)

  1. f is assigned the function returned by the lambda.
  2. lambda defines the function that takes a parameter (called append).
  3. (define cons (append "ugly" "confusing")) is not a function per se, but calls append with the two strings as parameter and assigns the result to cons.
  4. inside the let block, append is re-assigned a different value, the symbol this-was.
  5. the let block creates a list of append (which now contains 'this-was) and cons (which contains '("ugly" "confusing") from 3 above
  6. since 5 is the last statement that value is returned by the whole function which is called f
  7. f is called with the parameter list (the list function). which gets passed as the parameter append. And this is why 3 above creates a list '("ugly" "confusing") which gets assigned to cons.

Hope that cleared up things a bit. Cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜