Last active
December 6, 2017 00:46
-
-
Save bergwerf/97ea34daba17e7036215b8abc1df7f80 to your computer and use it in GitHub Desktop.
Dart pattern matching like Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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