File: Main.hx

package info (click to toggle)
haxe 1%3A4.3.7-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 44,520 kB
  • sloc: ml: 137,268; ansic: 2,491; makefile: 456; java: 386; cs: 336; cpp: 318; python: 318; sh: 75; objc: 64; php: 50; xml: 31; javascript: 11
file content (50 lines) | stat: -rw-r--r-- 1,233 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Main {
	static function main() {
		getAnswer().next(v -> switch v {
			case 42: 'Perfect!';
			case 40, 41, 43, 44: 'Close enough!';
			default: new NotError();
		}).handle(o -> trace(Std.string(o)));
	}

	static function getAnswer():Promise<Int>
		return 3 + 39;
}

class NotError {
	public function new() {}
}

abstract Promise<T>((handler:(result:Outcome<T, NotError>) -> Void) -> Void) {
	inline function new(f)
		this = f;

	public function next<X>(transform:Next<T, X>):Promise<X>
		return new Promise(handler -> this(o -> switch o {
			case Success(v): transform(v).handle(handler);
			case Failure(e): handler(Failure(e));
		}));

	@:from static function ofOutcome<T>(o:Outcome<T, NotError>):Promise<T>
		return new Promise<T>(h -> h(o));

	@:from static function ofValue<T>(v:T):Promise<T>
		return ofOutcome(Success(v));

	@:from static function ofError<T>(e:NotError):Promise<T>
		return ofOutcome(Failure(e));

	public function handle(cb)
		this(cb);
}

@:callable
abstract Next<In, Out>(In->Promise<Out>) from In->Promise<Out> {
	@:from(ignoredByInference) static function ofSync<In, Out>(f:In->Out):Next<In, Out>
		return v -> (f(v) : Promise<Out>);
}

enum Outcome<T, E> {
	Success(data:T);
	Failure(error:E);
}