pipe<T, R> function

R Function(T) pipe<T, R>(
  1. List<R Function(dynamic)> fns
)

Builds a function that threads its input left-to-right through fns, passing each result to the next. Throws a StateError if the final value is not assignable to R.

Example:

final f = pipe<int, int>([(x) => x + 1, (x) => x * 2]);
f(3); // 8

Audited: 2026-06-12 11:26 EDT

Implementation

R Function(T) pipe<T, R>(List<R Function(dynamic)> fns) => (T x) {
  dynamic v = x;
  for (final R Function(dynamic) f in fns) {
    v = f(v);
  }
  if (v is R) return v;
  throw StateError('pipe: result is ${v.runtimeType}, expected $R');
};