I am reading about local definitions in the book, and I came across this example-
(local ((define (f x) (+ x 5))
(define (g alon)
(cond
[(empty? alon) empty]
[else (cons (f (first alon)) (g (rest alon)))])))
(g (list 1 2 3)))
what exactly does local
do here?
local
is documented either in here as part of one of the HtDP languages or in here as part of the local
module. Let's see each one in turn. First the one in HtDP:
(local [definition ...] expression)
Groups related definitions for use in expression. Each definition can be either a define or a define-struct. When evaluating local, each definition is evaluated in order, and finally the body expression is evaluated. Only the expressions within the local (including the right-hand-sides of the definitions and the expression) may refer to the names defined by the definitions. If a name defined in the local is the same as a top-level binding, the inner one “shadows” the outer one. That is, inside the local, any references to that name refer to the inner one.
And next, the one in the local
module:
(local [definition ...] body ...+)
Like letrec-syntaxes+values, except that the bindings are expressed in the same way as in the top-level or in a module body: using define, define-values, define-syntax, struct, etc. Definitions are distinguished from non-definitions by partially expanding definition forms (see Partial Expansion). As in the top-level or in a module body, a begin-wrapped sequence is spliced into the sequence of definitions.
So depending on the language/modules in use, you'll know which local
was the one you found. And clearly, it's not a standard special form.
Local used to define some helper functions in the scope of a specific function. For example I am writing a function to add 5 to all elements of the given list ,
(define (add-5-to-list list)
(local
( ;; definition area start
(define (f x) (+ x 5))
(define (g alon)
(cond
[(empty? alon) empty]
[else (cons (f (first alon))
(g (rest alon)))]))
) ;; definition area end
(g list)
) ;; local end
) ;; define end
You can define as many function as you like in local. But you can use only in the scope of the main function (here the main function is add-5-to-list).