local in racket

一笑奈何 提交于 2019-12-10 16:59:10

问题


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?


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/15236851/local-in-racket

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!