Counter
1 About
1.1 The library
(require counter) | package: counter |
counter is a very simple OOP-like library providing two functions for creating simple "counter" closures: make-meter & make-counter.
Those functions can be utilized for logging, for debugging output of console applications or just counting iteration times of some other functions.
The core library is written in pure scheme and can be utilized by probably most scheme implamentations.
Know limitations are that the counter can only count up. To have a more freeform way use structs, objects, make-parameter or just utilize set!.
1.2 Upstream
The upstream repository can be found on GitLab.
1.3 License
Counter is available in Public Domain or under the CC0 License.
2 Alternative
As described previously a simple set! can be used to manage "counters" in a similar fashion.
With counter similar code would look like:
> (define c (make-counter 0)) > (c 'run) 1
> (c 'get 'val) 1
> (c 'runs 1) 2
> (c 'runs 0) 2
Benefits of using make-counter over set! are less code (which is also more DRY). Also the number of times the growth-procedure is ran can be specified. If the number of runs is zero or less only the value of the counter is returned.
3 Exported functions
procedure
(make-meter init-val init-growth-procedure init-interval) → procedure? init-val : number? init-growth-procedure : procedure? init-interval : number?
Example: starting value is 1 and then it is multipled by 2 on each call.
(define m (make-meter 1 * 2))
procedure
(make-counter start) → procedure?
start : number?
Example: starting value is 0 and then it is increased by 1 on each call.
(define c (make-counter 0))
4 Examples
(define c (make-counter 0))
> (define c (make-counter 0)) > (procedure? c) #t
> (define c (make-counter 0)) > (procedure? (c 'run)) #f
> (define c (make-counter 0)) > (c 'run) 1
> (define c (make-counter 0)) > (c 'runs 2) 2
> (define c (make-counter 0)) > (c #t) 1
(c 'set 'val 99)
> (define c (make-counter 0)) > (c 'set 'val 99) > (c 'get 'val) 99
Also check out tests.rkt included in this project.