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_withdraw(balance, amount_stream):
    return pair(balance,
                lambda: stream_withdraw(balance - head(amount_stream),
                                        stream_tail(amount_stream)))

my_amounts = pair(50, lambda: pair(100, lambda: pair(40, None)))
my_account_stream = stream_withdraw(200, my_amounts)
print(stream_ref(my_account_stream, 2))

# expected: 50
