Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

curry memoize by default. #146

Merged
merged 3 commits into from
Mar 19, 2014
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions examples/fib.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,9 @@ def fib(n):
fib = memoize(fib)


# Provide a cache with initial values to `memoize`
from toolz import curry


@curry(memoize, cache={0: 0, 1: 1})
# Provide a cache with initial values to `memoize`. This works as a decorator
# because `memoize` is curried (see `toolz.curry`) by default.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recommend skipping this explanation. I don't think many of our readers will know that this is strange and the reference to curry probably makes some people tune out.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. Should I remove the comment in the docstring too?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I say keep that one.

@memoize(cache={0: 0, 1: 1})
def fib(n):
""" Functional definition of Fibonacci numbers with initial terms cached.

Expand Down
2 changes: 1 addition & 1 deletion toolz/curried.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def nargs(f):
def should_curry(f):
do_curry = set((toolz.map, toolz.filter, toolz.sorted, toolz.reduce))
return (callable(f) and nargs(f) and nargs(f) > 1
or f in do_curry)
and not isinstance(f, curry) or f in do_curry)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead I recommend making curry idempotent. curry(curry(f)) -> curry(f)



d = dict((name, curry(f) if '__' not in name and should_curry(f) else f)
Expand Down
121 changes: 65 additions & 56 deletions toolz/functoolz/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,62 +80,6 @@ def evalform_back(val, form):
return reduce(evalform_back, forms, val)


def memoize(func, cache=None):
""" Cache a function's result for speedy future evaluation

Considerations:
Trades memory for speed.
Only use on pure functions.

>>> def add(x, y): return x + y
>>> add = memoize(add)

Or use as a decorator

>>> @memoize
... def add(x, y):
... return x + y
"""
if cache is None:
cache = {}

try:
spec = inspect.getargspec(func)
may_have_kwargs = bool(not spec or spec.keywords or spec.defaults)
# Is unary function (single arg, no variadic argument or keywords)?
is_unary = (spec and spec.varargs is None and not may_have_kwargs
and len(spec.args) == 1)
except TypeError:
may_have_kwargs = True
is_unary = False

def memof(*args, **kwargs):
try:
if is_unary:
key = args[0]
elif may_have_kwargs:
key = (args, frozenset(kwargs.items()))
else:
key = args
in_cache = key in cache
except TypeError:
raise TypeError("Arguments to memoized function must be hashable")

if in_cache:
return cache[key]
else:
result = func(*args, **kwargs)
cache[key] = result
return result

try:
memof.__name__ = func.__name__
except AttributeError:
pass
memof.__doc__ = func.__doc__
return memof


def _num_required_args(func):
""" Number of args for func

Expand Down Expand Up @@ -239,6 +183,71 @@ def __call__(self, *args, **_kwargs):
return curry(self.func, *args, **kwargs)


@curry
def memoize(func, cache=None):
""" Cache a function's result for speedy future evaluation

Considerations:
Trades memory for speed.
Only use on pure functions.

>>> def add(x, y): return x + y
>>> add = memoize(add)

Or use as a decorator

>>> @memoize
... def add(x, y):
... return x + y

Use the ``cache`` keyword to provide a dict-like object as an initial cache

>>> @memoize(cache={(1, 2): 3})
... def add(x, y):
... return x + y

Note that the above works as a decorator because ``memoize`` is curried.
"""
if cache is None:
cache = {}

try:
spec = inspect.getargspec(func)
may_have_kwargs = bool(not spec or spec.keywords or spec.defaults)
# Is unary function (single arg, no variadic argument or keywords)?
is_unary = (spec and spec.varargs is None and not may_have_kwargs
and len(spec.args) == 1)
except TypeError:
may_have_kwargs = True
is_unary = False

def memof(*args, **kwargs):
try:
if is_unary:
key = args[0]
elif may_have_kwargs:
key = (args, frozenset(kwargs.items()))
else:
key = args
in_cache = key in cache
except TypeError:
raise TypeError("Arguments to memoized function must be hashable")

if in_cache:
return cache[key]
else:
result = func(*args, **kwargs)
cache[key] = result
return result

try:
memof.__name__ = func.__name__
except AttributeError:
pass
memof.__doc__ = func.__doc__
return memof


class Compose(object):
""" A composition of functions

Expand Down
9 changes: 9 additions & 0 deletions toolz/functoolz/tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,15 @@ def test_memoize_key_signature():
assert mf(1) == 2


def test_memoize_curry_cache():
@memoize(cache={1: True})
def f(x):
return False

assert f(1) is True
assert f(2) is False


def test_curry_simple():
cmul = curry(mul)
double = cmul(2)
Expand Down