Skip to content

Instantly share code, notes, and snippets.

@bergwerf
Last active December 6, 2017 00:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bergwerf/97ea34daba17e7036215b8abc1df7f80 to your computer and use it in GitHub Desktop.
Save bergwerf/97ea34daba17e7036215b8abc1df7f80 to your computer and use it in GitHub Desktop.
Dart pattern matching like Rust
typedef bool Case<T>(T input);
Case<num> gt(num than) => (num x) => x != null && x > than;
Case nil = (instance) => instance == null;
O match<T, O>(T input, Map<dynamic, Function> cases) {
for (final _case in cases.keys) {
if (_case == input || (_case is Function && _case(input) == true)) {
return cases[_case]();
}
}
throw new RangeError('no matching case');
}
void main() {
final list = [null, 10, 100];
for (final x in list) {
print(match(x, {
10: () => 'x is 10!',
gt(10): () => 'x is greater than 10!',
nil: () => 'x is null'
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment