~nch/glue

ref: ea3a590e496ffd97d17b67879f3072aae73bc1c3 glue/dataflow.py -rw-r--r-- 1.3 KiB
ea3a590e — nc WIP attempt with generators 1 year, 4 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
from inspect import isgenerator
import functools

class _StreamHandle:
    def __init__(self, stream, i):
        self.stream = stream
        self.i = i

    def __iter__(self):
        return self

    def __next__(self):
        i = self.i
        self.i += 1 # stream advances...
        if i > len(self.stream.vals) - 1:
            return next(self.stream)
        else:
            return self.stream.vals[i]

    def __repr__(self):
        if self.stream.f:
            return f'<streamhandle {self.stream.f.__name__}>'
        else:
            return '<streamhandle>'

    def copy(self):
        return _StreamHandle(self.stream, self.i)

class _Stream:
    def __init__(self, f, *args):
        self.gen = f(*args)
        self.f = f
        self.vals = []

    def __iter__(self):
        return self

    def __next__(self):
        r = next(self.gen)
        if isinstance(r, _Stream) or isinstance(r, _StreamHandle):
            r = next(r)
        self.vals.append(r)
        return r

    def copy(self):
        return _StreamHandle(self, len(self.vals))

def stream(f):
    @functools.wraps(f)
    def g(*args):
        return _Stream(f, *args).copy()
    return g

@stream
def int_(i):
    while True:
        yield i

@stream
def fby(x, y):
    yield x
    while True:
        yield y

@stream
def next_(s):
    while True:
        yield next(s)