Urs Liska <li...@openlilylib.org> 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.


-- 
David Kastrup

_______________________________________________
lilypond-user mailing list
lilypond-user@gnu.org
https://lists.gnu.org/mailman/listinfo/lilypond-user

Reply via email to