~ntietz/hurl-lang

hurl-lang/lib/loop.hurl -rw-r--r-- 1.9 KiB
5c1b4984Nicole Tietz-Sokolskaya name 2 months ago
                                                                                
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
let loop = func(body, locals) {
    let new_locals = locals;
    try {
        body(locals);
    } catch (true) {
        loop(body, new_locals);
    } catch (false) {
        hurl new_locals;
    } catch as update {
        new_locals = update;
        return;
    };
};

let for = func(count, body, locals) {
    let iter = 1;

    let wrapped = func(locals) {
        let inner_locals = locals.1;

        let new_locals = inner_locals;

        try {
            body(inner_locals + [iter]);
        } catch as update {
            new_locals = update;
        };

        iter = iter + 1;

        toss [new_locals];
        hurl iter < count + 1;
    };

    try {
        loop(wrapped, [locals, 1, count]);
    } catch as retval {
        hurl retval.1;
    };
};

let until = func(cond, body, locals) {
    let wrapped = func(locals) {
        let again = false;
        try {
            body(locals);
        } catch as update {
            locals = update;
        };

        try {
            cond(locals);
        } catch as val {
            again = val;
        };

        toss locals;
        hurl ~again;
    };

    loop(wrapped, locals);
};

let for_each = func(list, body) {
    let index = 1;

    let chunk_size = 250;
    let num_chunks = ceil(len(list) / chunk_size);

    try {
        until(func(locals) {
            hurl index > len(list);
        }, func(locals) {
            let chunk_index = 1;
            try {
                until(func(locals) {
                    hurl (chunk_index > chunk_size) or (index > len(list));
                }, func(locals) {
                    body(at(list, index));
                    chunk_index = chunk_index + 1;
                    index = index + 1;
                    hurl locals;
                }, []);
            } catch as x {
            };

            hurl locals;
        }, []);
    } catch as x {
    };
};