guile-primer/8_closures.scm

27 lines
734 B
Scheme
Raw Normal View History

2024-03-12 00:44:56 +01:00
;; -*- geiser-scheme-implementation: guile -*-
(define (make-goldilocks smallest-ok biggest-ok)
(define (goldilocks n)
(cond ((< n smallest-ok) 'too-small)
((> n biggest-ok) 'too-big)
(else 'just-right)))
goldilocks)
(make-goldilocks 10 30) ; #<procedure goldilocks (n)>
(define goldi (make-goldilocks 10 30)) ; #<unspecified>
(goldi 7) ; too-small
(goldi 256) ; too-big
(goldi 22) ; just-right
(define (abstract-cons car-data cdr-data)
(lambda (method)
(cond ((eq? method 'car) car-data)
((eq? method 'cdr) cdr-data)
(else (error "Unknown method -- ABSTRACT-CONS" method)))))
(define our-cons (abstract-cons 'foo 'bar))
(our-cons 'car) ; foo
(our-cons 'cdr) ; bar