Skip to content

Instantly share code, notes, and snippets.

@matux
Created July 21, 2022 15:28
Show Gist options
  • Save matux/c9d5c5717efd88f1b9504fb7a6e4d8c2 to your computer and use it in GitHub Desktop.
Save matux/c9d5c5717efd88f1b9504fb7a6e4d8c2 to your computer and use it in GitHub Desktop.
Operators for composition of endomorphism in Dart
// Here be dragons //
extension _EndomorphicComposition<T> on T Function(T) {
/// Mathematical composition of endomorphisms.
///
/// In mathematics, function composition is an operation ∘ that takes two
/// functions ƒ and g, and produces a function h = g ∘ ƒ such that
/// h(x) = g(ƒ(x)).
///
/// An endomorphism is any morphism ƒ whose domain is equal to its codomain
/// such that ƒ: a -> a or T ƒ(T)
T Function(T) operator <<(T Function(T) f) => (x) => f(this(x));
/// Forward composition of endomorphisms.
T Function(T) operator >>(T Function(T) f) => (x) => this(f(x));
}
int plusOne(int x) => x + 1;
int mulTwo(int x) => x * 2;
void thing() {
final xs = [1, 2, 3, 4];
final ys = xs.map(plusOne >> mulTwo); // [4, 6, 8, 10]
final zs = xs.map(plusOne << mulTwo); // [3, 5, 7, 9]
print('$ys\n$zs');
// imperatively
var yys = <int>[];
for (final x in xs) {
// yys.add(mulTwo(plusOne(x)));
final y = plusOne(x);
final z = mulTwo(y);
yys.add(z);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment