guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Define in let


From: Panicz Maciej Godek
Subject: Re: Define in let
Date: Wed, 21 Aug 2013 08:52:02 +0200


2013/8/20 David Pirotte <address@hidden>
Hello,

> It seems following is invalid:
>
>    (let ((a 2))
>         (define (foo x) (+ a x)))
>
> I prefer to reduce scope of variable as much as possible, so
> I find this restriction unconvinent. Is is part of standard or technical
> limitation? Is it any workaround?

The Scheme's idiomatic way to achieve the effect that you 
probably want would be
(define foo #f)
(let ((a 2))
  (set! foo (lambda (x) (+ a x))))

Although it allows to achieve the desired effect, it doesn't
express the programmer's intention quite clearly.
If you're interested, I recently wrote a macro that would
allow to get the same in a IMHO slightly more elegant way, i.e.

(publish
  (define (foo x) (+ a x))
 where
  (define a 2))
 
The macro's definition (procedural) follows.
Regards.

=============================
(define-macro (publish . definitions)
  (define (interface-name interface)
    (match interface
      ((head . tail)
       (interface-name head))
      ((? symbol? name)
       name)))
  (let-values (((public-definitions where&private-definitions)
                (split-before (equals? 'where) definitions)))
    `(begin ,@(map (match-lambda
                       ((define-variant interface . body)
                        `(define ,(interface-name interface) #f)))
                   public-definitions)
            (let ()
              ,@(match where&private-definitions
                  (('where . private-definitions)
                   private-definitions)
                  (() '()))
              ,@(map (match-lambda
                         ((define-variant interface . body)
                          (let ((name (interface-name interface)))
                            `(set! ,name
                                   (let ()
                                     (,define-variant ,interface . ,body)
                                     ,name)))))
                     public-definitions)))))


reply via email to

[Prev in Thread] Current Thread [Next in Thread]