#lang racket (define-namespace-anchor a) (define ns (namespace-anchor->namespace a)) ;; clasic (define prod1 (λ (x y) (displayln "prod") (if x (* y (+ y 1)) 0))) (define test1 (λ (x) (let ((y 5)) (prod1 x (and (display "y ") y))))) (test1 #f) (test1 #t) (displayln "------ ^ direct") ;; quote + eval (define prod2 (λ (x y) (displayln "prod") (if x (* (eval y ns) (+ (eval y ns) 1)) 0))) (define test2 (λ (x) (let ((y 5)) (prod2 x (quote (and (display "y ") y)))))) ;(test2 #f) (test2 #t) (displayln "------ ^ quote & eval") ; paranteză: închideri funcționale (define w 1) (define (create x y) (let ((z (* x y)) ; 2 (t (+ x y))) ; 3 (display "here\n") (λ (a) (+ a x y z t w)) ; 12 )) (define (make-call) ( (create 1 2) 3)) ;; inchidere λ (define prod3 (λ (x y) (displayln "prod") (if x (* (y) (+ (y) 1)) 0))) (define test3 (λ (x) (let ((y 5)) (prod3 x (λ () (and (display "y ") y)))))) (test3 #f) (test3 #t) (displayln "------ ^ închideri λ") ;; promisiuni (define prod4 (λ (x y) (displayln "prod") (if x (* (force y) (+ (force y) 1)) 0))) (define test4 (λ (x) (let ((y 5)) (prod4 x (delay (begin (display "y ") y)))))) (test4 #f) (test4 #t) (displayln "------ ^ promisiuni") (define y 2) (delay (and (display "y ") y)) ; -> prim rang (displayln "------") ;; ============================================================================ ;; creez un macro pentru a abstractiza mecanismul de întârziere ;; cu inchideri ;(define-syntax-rule (pack computation) (λ () computation) ) ;(define (unpack package) (package) ) ;; cu promisiuni (define-syntax-rule (pack computation) (delay computation) ) (define (unpack package) (force package) ) ;; pack - unpack (define prod5 (λ (x y) ; y is a package (displayln "prod") (if x (* (unpack y) (+ (unpack y) 1)) 0))) (define test5 (λ (x) (let ((y 5)) (prod5 x (pack (and (display "y ") y)))))) (test5 #f) (test5 #t) (displayln "------ ^ pack & unpack")