Local in racket

I read about local definitions in a book, and I came across this example -

(local ((define (fx) (+ 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?

+4
source share
2 answers

local 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 in turn. First in HtDP:

(local [definition ...] expression) Group-related definitions to use in the expression. Each definition can be either define or define-struct. When evaluating locality, each definition is evaluated in order, and finally, the expression of the body is calculated. Only expressions inside the local (including the right-hand sides of definitions and expressions) can refer to names defined by definitions. If the name specified in the local matches the name of the top level, the inner "shadow" of the outer. That is, inside the local, any links to this name refer to the internal.

And further, in the local module:

(local [definition ...] body ...+) Similar to letrec-syntaxes + values, except that bindings are expressed in the same way as at the top level or in a module: using define, define-values, define-syntax, struct etc. Definitions differ from non-definitions by partially expanding the definition forms (see Section "Partial Extensions"). As at the top level or in the module, the sequence with the final completion is spliced ​​into a sequence of definitions.

So, depending on the language / modules used, you will find out which local was the one you found. And, obviously, this is not a standard special form.

+6
source

Local used to define some auxiliary functions in the field of a specific function. For example, I am writing a function to add 5 to all elements of a given list,

 (define (add-5-to-list list) (local ( ;; definition area start (define (fx) (+ 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 functions as you want in local mode. But you can use it only within the framework of the main function (here the main function is to add-5-to-list).

+1
source

All Articles