newprint
newprint

Reputation: 7136

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-was])
        (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 !

Upvotes: 1

Views: 551

Answers (2)

Sujoy
Sujoy

Reputation: 8299

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!

Upvotes: 4

Eli Barzilay
Eli Barzilay

Reputation: 29546

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.

Upvotes: 5

Related Questions