Skip to content

Instantly share code, notes, and snippets.

@Grohden
Last active July 2, 2020 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grohden/746f8f9b09a87e852dca5d3bef91cb5c to your computer and use it in GitHub Desktop.
Save Grohden/746f8f9b09a87e852dca5d3bef91cb5c to your computer and use it in GitHub Desktop.
Pain and suffering by forcing ramda into everything (in this case, dart)
library flambda;
typedef Predicate<T> = bool Function(T);
class Case<T, R> {
Case(this.predicate, this.whenTrue);
factory Case.otherwise(R Function(T) whenTrue) {
return Case((T) => true, whenTrue);
}
Predicate<T> predicate;
final R Function(T) whenTrue;
}
R Function(T) ifElse<R, T>(
Predicate<T> predicate,
R Function(T) whenTrue,
R Function(T) whenFalse
) => (arg) {
if(predicate(arg)){
return whenTrue(arg);
} else {
return whenFalse(arg);
}
};
T Function(T) when<T>(
Predicate<T> predicate,
T Function(T) whenTrue
) => (arg) {
if(predicate(arg)){
return whenTrue(arg);
} else {
return arg;
}
};
R Function(T) always<R, T>(R arg) => (ignored) => arg;
Predicate<T> complement<T>(Predicate<T> pred) => (arg) => !pred(arg);
Predicate<S> eq<F, S>(F first) => (second) => first == second;
Predicate<S> notEq<F, S>(F first) => complement(eq(first));
Predicate isNil = eq(null);
R Function(T) cond<T, R>(List<Case<T, R>> cases) {
return (argument) {
final result = cases.firstWhere(
(condition) => condition.predicate(argument)
);
return result?.whenTrue(argument);
};
}
// need to rewrite the old file using proper safe types
typedef Predicate<T> = bool Function(T);
typedef Comparator<T, S> = Predicate<S> Function(S second);
// Should we consider dartz? I think it's too overbloated.
// BTW: type system go BRRRR
/// Takes a predicate and returns another predicate
/// that negate it's result
Predicate<T> complement<T>(Predicate<T> predicate) =>
(second) => !predicate(second);
/// Loosen compares F to S (they don't need to be the same type
Predicate<S> loosenEq<F, S>(F first) => (second) => first == second;
/// Complement of [loosenEq]
Predicate<S> loosenNotEq<F, S>(F first) => complement(loosenEq<F, S>(first));
/// Single T [loosenEq]
Predicate<T> eq<T>(T first) => loosenEq<T, T>(first);
/// Single T [loosenNotEq]
Predicate<T> notEq<T>(T first) => loosenNotEq<T, T>(first);
@jeovazero
Copy link

ramdart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment