Counter
1 About
1.1 The library
1.2 Upstream
1.3 License
2 Alternative
3 Exported functions
make-meter
make-counter
4 Examples
8.2

Counter

Maciej Barć <xgqt@riseup.net>

    1 About

      1.1 The library

      1.2 Upstream

      1.3 License

    2 Alternative

    3 Exported functions

    4 Examples

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.

(define c 0)
(set! c (+ c 1))
c
1
(set! c (+ c 1))
c
2

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?
Returns a new closure function which when called with ’run will execute growth-procedure on val (initially val = init-val) and interval replacing val with new value and, then return that new value.

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?
Uses make-meter to create a function which uses + as growth-procedure and has interval equal to 1.

Example: starting value is 0 and then it is increased by 1 on each call.

(define c (make-counter 0))

4 Examples

Make an new counter c

(define c (make-counter 0))

Check type of c

(procedure? c)

> #t

Check type of (c ’run)

(procedure? (c 'run))

> #f

Execute (c ’run) function

((c 'run))

> 1

Execute (c ’runs) function two times

(c 'runs 2)

> 3

To execute (c ’run) any argument may be passed to c

(c #t)

> 4

Some more OOP - set the value inside c closure to 99

(c 'set 'val 99)

And check the value

(c 'get 'val)

> 99

Also check out tests.rkt included in this project.