Example #1
0
    while True:
        yield element


def powerset(iterable):
    """Yields all possible subsets of the iterable
        >>> list(powerset([1,2,3]))
        [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
    """
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))


# Return a tuple containing the next element in the sequence,
# and an iterable containing the rest of the sequence.
split = compose(lambda iterator, next=next: (next(iterator), iterator), iter)


def take(n, iterable, islice=islice):
    """
    Take the first n elements of the given iterable.
    """
    return islice(iterable, n)


def unique(iterable, filterfalse=filterfalse):
    """
    Return only unique elements from the sequence.
    """
    seen = set()
    add = seen.add
Example #2
0
 def juxt(cls, func, *funcs):
     return cls(compose(lift(func), juxt(*funcs)))
Example #3
0
def constant(x):
    """Close x under an anonymous function."""
    return lambda *args, **kwargs: x


@contextmanager
def context(func, *args, **kwargs):
    """Return a context for lazily evaluating a function with given input."""
    yield func(*args, **kwargs)


# Return the number of position arguments in the given function.
nargs = compose(
    partial(reduce, operator.sub),
    partial(map, len),
    compact,
    operator.attrgetter('args', 'defaults'),
    getargspec
)


def curry(func, n=None):
    """Curry a function for up to n arguments, where by default n is the number
    of fixed, unnamed arguments in the function defintion.
    """

    if n is None:
        n = nargs(func)

    # @wraps(func)
    def curried(*args, **kwargs):
Example #4
0
 def compose(cls, *funcs):
     return cls(compose(*funcs))
Example #5
0
 def test_compose(self):
     c = common.compose(lambda x: x + 2, lambda y: y ** 2)
     self.assertEqual(c(12), 146)