count<E, A> function

Parser<E, List<A>> count<E, A>(
  1. int n,
  2. Parser<E, A> p
)

Exactly n occurrences of p.

Implementation

Parser<E, List<A>> count<E, A>(int n, Parser<E, A> p) {
  if (n <= 0) return Succeed<E, List<A>>(<A>[]);
  Parser<E, List<A>> loop(int remaining, List<A> acc) {
    if (remaining <= 0) return Succeed<E, List<A>>(acc);
    return FlatMap<E, A, List<A>>(p, (A v) => loop(remaining - 1, [...acc, v]));
  }

  return loop(n, []);
}