def stream_tail(stream):
    return tail(stream)()
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))
def stream_append(s1, s2):
    return (s2
            if is_none(s1)
            else pair(head(s1),
                      lambda: stream_append(stream_tail(s1), s2)))
def pairs(s, t):
    return pair(llist(head(s), head(t)),
                lambda: stream_append(
                            stream_map(lambda x: llist(head(s), x),
                                       stream_tail(t)),
                            pairs(stream_tail(s), stream_tail(t))))
max_display = 9
def display_stream(s):
    def display_stream_iter(st, n):
        if is_none(st):
            pass
        elif n == 0:
            display("", "...")
        else:
            display(head(st))
            display_stream_iter(stream_tail(st), n - 1)
    display_stream_iter(s, max_display)
def integers_starting_from(n):
    return pair(n, lambda: integers_starting_from(n + 1))
integers = integers_starting_from(1)
print(pairs(integers, integers))

print(stream_ref(pairs(integers, integers), 8))

# expected: [ 1, [ 9, null ] ]
