counter

Types

A Counter is a specialized dictionary used for counting the occurrences of items. Counter is implemented using the gleam/dict module.

pub opaque type Counter(a)

Functions

pub fn add(
  counter_1: Counter(a),
  counter_2: Counter(a),
) -> Counter(a)

Add the counts from two Counters into a new Counter.

pub fn elements(counter: Counter(a)) -> List(a)

Returns a non-unique list of all the items in the Counter. Each item will be repeated in the list the number of times it was inserted into the Counter. Do not write code that relies on the order elements are returned by this function as it may change in later versions of Gleam or Erlang.

pub fn from_dict(d: Dict(a, Int)) -> Counter(a)

Creates a Counter from a gleam/dict of item-count pairs.

pub fn from_list(items: List(a)) -> Counter(a)

Creates a Counter from a list of items.

pub fn get(counter: Counter(a), item: a) -> Int

Returns the number of times an item has been inserted into the Counter.

pub fn insert(counter: Counter(a), item: a) -> Counter(a)

Inserts an item into the Counter.

pub fn keys(counter: Counter(a)) -> List(a)

Returns a list of all the unique items in the Counter. Do not write code that relies on the order keys are returned by this function as it may change in later versions of Gleam or Erlang.

pub fn most_common(counter: Counter(a)) -> List(#(a, Int))

Returns a list containing all item-count tuples, sorted by count, in descending order.

pub fn most_common_n(
  counter: Counter(a),
  n: Int,
) -> List(#(a, Int))

Returns a list of item-count tuples containing the top n most frequent items, sorted by count, in descending order.

pub fn new() -> Counter(a)

Creates a new empty Counter.

pub fn subtract(
  counter_1: Counter(a),
  counter_2: Counter(a),
) -> Counter(a)

Subtracts the counts in the second Counter from the first Counter, returning a new Counter with the results. Only items present in both Counters will be used when subtracting counts from the first Counter and any item with a count of zero or less will be omitted from the new Counter.

pub fn to_dict(counter: Counter(a)) -> Dict(a, Int)

Returns the underlying gleam/dict of the Counter.

pub fn to_list(counter: Counter(a)) -> List(#(a, Int))

Returns a list of item-count tuples. Do not write code that relies on the order tuples are returned by this function as it may change in later versions of Gleam or Erlang.

pub fn total(counter: Counter(a)) -> Int

Returns the sum of all counts in the Counter.

pub fn unique_size(counter: Counter(a)) -> Int

Returns the number of unique items in the Counter.

pub fn update(counter: Counter(a), items: List(a)) -> Counter(a)

Updates the Counter from a list of items.

pub fn values(counter: Counter(a)) -> List(Int)

Returns a list of all the counts in the Counter. Do not write code that relies on the order values are returned by this function as it may change in later versions of Gleam or Erlang.

Search Document