ferrum icon indicating copy to clipboard operation
ferrum copied to clipboard

Pattern matching on sequences: Providing a lazy version of [head, ...tail]

Open koraa opened this issue 5 years ago • 0 comments

Implement the standard pattern matching structure [head, ...tail] but using iterators…so with lazyness.

// Split the given sequence into head and tail
const pop = (seq) => {
  const i = iter(seq);
  const v = next(i);
  return [i, v];
};

const tryPop = ...

// Split the given sequence into an array and the rest of the iterator
const popn = (seq, headLen) => …
const tryPopn = (seq, headLen) => …

// Version of fold that will fail if the sequence has zero elements 
const foldl1 = (seq, fn) => {
  const [i, v] = pop(seq);
  return foldl(i, v, fn);
};
// Fold but without initial element; this will just use the default value in case the sequence is empty but always start folding with the first element from the sequence
const tryFoldl1 = (seq, default, fn) => {
  const None = Symbol();
  const [it, v] = tryPop(seq);
  return v === None ? default : foldl(it, v, fn);
};

const foldr1 = …
const tryFoldr1 = …

koraa avatar Nov 09 '20 17:11 koraa