lilypond-user
[Top][All Lists]
Advanced

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

Re: check undefined variable scheme


From: Urs Liska
Subject: Re: check undefined variable scheme
Date: Thu, 24 May 2018 10:50:03 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.7.0



Am 24.05.2018 um 10:46 schrieb David Kastrup:
Urs Liska <address@hidden> writes:

Am 24.05.2018 um 09:56 schrieb Gianmaria Lari:
The following function increase a counter by 1 and return it as string

     #(define count 0)
     #(define (nextcount) (begin
                           (set! count (+ 1 count))
                           (number->string count)
                           )
        )

Is my code ok, or I should write it in a different way?
Two observations:
- You don't need that (begin ...) wrapper because the procedure
definition already behaves as such
- You shouldn't use reserved words for variable names, so I'd use
'counter' instead.
Is it possible to define "count" inside the function just in case it
is undefined?
Yes, see:

\version "2.19.80"

#(define (nextcount)
    (if (not (defined? 'counter)) (ly:parser-define! 'counter 0))
    (set! counter (+ 1 counter))
    (number->string counter)
    )
You actually don't need to define it externally:

     #(define nextcount
       (let ((counter 0))
        (lambda ()
         (set! counter (1+ counter))
         (number->string counter))))

     $(nextcount)

     $(nextcount)

will work just fine.



Ah yes, that's more idiomatic and (thus) elegant.
Gianmaria, if you want to understand what's happening there read https://www.gnu.org/software/guile/docs/docs-1.8/guile-ref/Closure.html#Closure




reply via email to

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