def stream_tail(stream):
    return tail(stream)()
def memo(fun):
    already_run = False
    result = None
    def memoized():
        nonlocal already_run, result
        if not already_run:
            result = fun()
            already_run = True
            return result
        else:
            return result
    return memoized
def stream_map_2(f, s1, s2):
    return (None
            if is_none(s1) and is_none(s2)
            else error("unexpected argument -- stream_map_2", None)
            if is_none(s1) or is_none(s2)
            else pair(f(head(s1), head(s2)),
                      memo(lambda: stream_map_2(f, stream_tail(s1),
                                                stream_tail(s2)))))
def add_streams(s1, s2):
    return stream_map_2(lambda x1, x2: x1 + x2, s1, s2)
ones = pair(1, lambda: ones)
def stream_ref(s, n):
    return (head(s)
            if n == 0
            else stream_ref(stream_tail(s), n - 1))

def stream_map(f, s):
    return (None
            if is_none(s)
            else pair(f(head(s)),
                      lambda: stream_map(f, stream_tail(s))))

def stream_for_each(fun, s):
    if is_none(s):
        return True
    else:
        fun(head(s))
        return stream_for_each(fun, stream_tail(s))
integers = pair(1, lambda: add_streams(ones, integers))

print(stream_ref(integers, 50))

# expected: 51
