adobe / ferrum

Features from the rust language in javascript: Provides Traits/Type classes & a hashing infrastructure and an advanced library for working with sequences/iterators in js
https://www.ferrumjs.org
Apache License 2.0
519 stars 25 forks source link

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

Open koraa opened 4 years ago

koraa commented 4 years ago

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 = …