~nch/glue

ref: 50333171e5b5973cdef9c6e8d045750a3a0936e6 glue/dataflow.py -rw-r--r-- 1.7 KiB
50333171 — nc WIP this seems(?) to be working 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from inspect import isgenerator
import functools

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

    def __iter__(self):
        return self

    @property
    def first(self):
        return self.stream.vals[0]

    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)

    def __add__(self, other):
        def addf(a, b):
            while True:
                yield next(a) + next(b)
        return stream(addf)(self, other)

    def where(self, **kwargs):
        pass # TODO

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 var(name):
    pass

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