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)
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 scale_stream(stream, factor):
    return stream_map(lambda x: x * factor,
                      stream)
def integral(integrand, initial_value, dt):
    integ = pair(initial_value,
                 lambda: add_streams(scale_stream(integrand, dt),
                                     integ))
    return integ

def numbers_starting_from(t, dt):
    return pair(t,
                lambda: numbers_starting_from(t + dt, dt))

dt = 0.01
linear = numbers_starting_from(0, dt)
linear_integral = integral(linear, 0, dt)
# computing integral from 0 to 3 of f(x) = x
# (the integral is g(x) = 0.5 x^2, and therefore
# the result is near 0.5 * 3^2 = 4.5)
print(stream_ref(linear_integral, round(3 / dt)))

# expected: 4.484999999999992
