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 :)
f
is assigned the function returned by thelambda
.lambda
defines the function that takes a parameter (calledappend
).(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.- inside the
let
block, append is re-assigned a different value, the symbolthis-was
. - the let block creates a list of
append
(which now contains'this-was
) andcons
(which contains'("ugly" "confusing")
from 3 above - since 5 is the last statement that value is returned by the whole function which is called
f
f
is called with the parameterlist
(thelist
function). which gets passed as the parameter append. And this is why 3 above creates a list'("ugly" "confusing")
which gets assigned tocons
.
Hope that cleared up things a bit. Cheers!
精彩评论