def reduceby(iterable, keyfunc, reducefunc, init):
    """Combination of ``itertools.groupby()`` and  ``reduce()``.

    This generator iterates over the iterable. The values are reduced using
    ``reducefunc`` and ``init`` as long as ``keyfunc(item)`` returns the same
    value.

    A possible use case would be to aggregate website visits and to group them
    by month. The corresponding SQL statement would be::

        SELECT SUM(visit_count) FROM visits GROUP BY month;

    Example::

        >>> keyfunc = lambda x: x % 2 == 0
        >>> reducefunc = lambda x, y: x + y
        >>> values = [1, 3, 5, 6, 8, 11]
        >>> groups = utils.reduceby(values, keyfunc, reducefunc, 0)
        >>> groups
        <generator object reduceby at 0xedc5a0>
        >>> list(groups)
        [9, 14, 11]

    :param iterable: An iterable to reduce. The iterable should be presorted.
    :param keyfunc: A key function. It should return the same value for all
        items belonging to the same group.
    :param reducefunc: The reduce function.
    :param init: The initial value for the reduction.
    :returns: A generator returning the reduced groups.
    :rtype: generator

    """
    first = True
    oldkey = None
    accum_value = init
    for i in iter(iterable):
        key = keyfunc(i)
        if first:
            oldkey = key
            first = False
        elif key != oldkey:
            yield accum_value
            accum_value = init
            oldkey = key
        accum_value = reducefunc(accum_value, i)
    yield accum_value
