x-lang

← Index

x/type/counter

A counting map, homed on the Counter class.

Dict-backed: key kinds and equality are Dict’s; absent keys read 0; most-common rides the stable List sort, so equal counts keep table order.

Class Counter

A counting map: (c add! x) tallies, (c get x) reads (0 when never seen), (c most-common) ranks. Backed by Dict, so key kinds and equality are Dict’s.

d

Member: data carried by a Counter instance.

(%d)

Instance method: called on a Counter instance.

(Counter make)

An empty counter.

Returns: Counter — A new empty counter

Examples:

((Counter make) total) => 0

(Counter from-list lst)

A counter holding one tally per list element.

Parameters:

Returns: Counter — The populated counter

Examples:

((Counter from-list (list "x" "y" "x")) get "x") => 2

(add! x . n)

Add n (default 1) to x’s tally. Returns the counter for chaining; a tally may go negative – the counter records what it is told.

Instance method: called on a Counter instance.

Parameters:

Returns: Counter — self

(get x)

x’s tally; 0 when x was never added – absence and zero read alike, the counting convention.

Instance method: called on a Counter instance.

Parameters:

Returns: INT — The tally

(del! x)

Drop x’s tally entirely (get returns 0 afterwards). Returns the counter for chaining.

Instance method: called on a Counter instance.

Parameters:

Returns: Counter — self

(total)

The sum of every tally.

Instance method: called on a Counter instance.

Returns: INT — Sum of counts

Examples:

(let ((c (Counter from-list (list 'a 'b 'a)))) (c total)) => 3

(keys)

Every value holding a tally (order unspecified – the Dict’s table order).

Instance method: called on a Counter instance.

Returns: LIST — The tallied values

(->alist)

The tallies as ((value . count) …), order unspecified.

Instance method: called on a Counter instance.

Returns: ALIST — (value . count) pairs

(most-common . n)

The tallies as ((value . count) …) sorted by count, largest first (ties in table order – the sort is stable); pass n for just the top n.

Instance method: called on a Counter instance.

Parameters:

Returns: ALIST — (value . count) pairs, descending by count

Examples:

(let ((c (Counter from-list (list 'a 'b 'a 'c 'a 'b)))) (c most-common 2)) => (('a . 3) ('b . 2))