Implementation of embedded functions in the diagram

What happens when I do the following?

(define ((func x) y)
    (if (zero? y)
        ((func x) 1)
        12))

I understand that I can do this:

(define curried (func 5))

And now I can use curries. What interests me is the definition of a function. Line

((func x) 1)

create a new lambda with x as an argument and then call it at 1? Or he is smarter than that, and he just reuses the existing one. (For example, if I do (curried 0), the string ((func x) 1)will be equivalent (curried 1)- does the PLAI circuit do?)

+2
source share
3 answers

The Scheme standard states that

(define (f x) 42) is short for (define f (lambda (x) 42)) .

A natural (non-standard) generalization entails:

(define ((f x) y) (list x y)) is short for (define (f x) (lambda (y) (list x y)))
                which is short for (define f (lambda (x) (lambda (y) (list x y))))

To check this, try an example in DrScheme

DrScheme, 4.1.3.3-svn5dec2008 [3m]. : ; : 384 .

(define ((x x) y) ( x y)) (f 1)

((f 1) 2) (1 2)

, , :

( h (f 1)) (h 2) (1 2) (h 3) (1 3)

"PLAI Scheme" DrScheme, , .

+8

, . , c-lambda c-define, -.

+2

soegaard - . , drscheme !

, :

:

(define ((substitute lv value) e)
  (cond [(LogicVar? e)
     (type-case LogicVar e
       [lv-any (id) (if (symbol=? id (lv-any-id lv))
                value
                e)]
       [lv-cons (f r) 
            (lv-cons ((substitute lv value) f)
                 ((substitute lv value) r))])]
    [(cons? e)
     (cons ((substitute lv value) (car e))
           ((substitute lv value) (cdr e)))]
    [else e]))

:

(define (substitute lv value)
  (local ([define inner
        (lambda (e)
          (cond [(LogicVar? e)
             (type-case LogicVar e
               [lv-any (id) (if (symbol=? id (lv-any-id lv))
                    value
                    e)]
               [lv-cons (f r) 
                (lv-cons (inner f)
                     (inner r))])]
            [(cons? e)
             (cons (inner (car e))
               (inner (cdr e)))]
            [else e]))])
    inner))

, ( , ), 1800 . , ( ):

(define (substitute lv value)
  (local ([define inner
        (lambda (e)
          (cond [(LogicVar? e)
             (type-case LogicVar e
               [lv-any (id) (if (symbol=? id (lv-any-id lv))
                    value
                    e)]
               [lv-cons (f r) 
                (lv-cons ((substitute lv value) f)
                     ((substitute lv value) r))])]
            [(cons? e)
             (cons ((substitute lv value) (car e))
               ((substitute lv value) (cdr e)))]
            [else e]))])
    inner))

It works in 2000 ms. Thus, there is a certain tendency to slow down if calls for substitution within the substitution replace each, creating a lambda, but this does not seem to apply to the label label.

0
source

Source: https://habr.com/ru/post/1545673/


All Articles