Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(79)

Side by Side Diff: tools/gardening/lib/src/try.dart

Issue 3005443002: Additional tools for gardening. (Closed)
Patch Set: Moved files from gardening_tools to gardening and incorporated changes from johnniwinther Created 3 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 import 'dart:async';
2
3 /// [Try] is similar to Haskell monad, where
4 /// a computation may throw an exception.
5 /// There is no checking of passing null into
6 /// the value, so be mindful.
7 class Try<T> {
8 final T _val;
9 final StackTrace _stackTrace;
10 final Exception _err;
11
12 Try.from(this._val)
13 : _err = null,
14 _stackTrace = null;
15
16 Try.fail(this._err, this._stackTrace) : _val = null;
17
18 Try<S> bind<S>(S f(T)) {
19 if (_err != null) {
20 return new Try.fail(_err, _stackTrace);
21 }
22 try {
23 return new Try<S>.from(f(_val));
24 } catch (ex, stackTrace) {
25 return new Try<S>.fail(ex, stackTrace);
26 }
27 }
28
29 Future<Try<S>> bindAsync<S>(Future<S> f(T)) async {
30 if (_err != null) {
31 return new Try.fail(_err, _stackTrace);
32 }
33 try {
34 return new Try.from(await f(_val));
35 } catch (ex, stackTrace) {
36 return new Try.fail(ex, stackTrace);
37 }
38 }
39
40 void fold(caseErr(Exception ex, StackTrace st), caseVal(T)) {
41 if (_err != null) {
42 caseErr(_err, _stackTrace);
43 } else {
44 caseVal(_val);
45 }
46 }
47
48 bool get isError => _err != null;
49
50 Exception get error => _err;
51 StackTrace get stackTrace => _stackTrace;
52
53 T get value => _val;
54
55 T getOrDefault(T defval) => _err != null ? defval : _val;
56 }
57
58 Try<T> tryStart<T>(T action()) {
59 return new Try<int>.from(0).bind<T>((dummy) => action());
60 }
61
62 Future<Try<T>> tryStartAsync<T>(Future<T> action()) {
63 return new Try<int>.from(0).bindAsync<T>((dummy) => action());
64 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698