| OLD | NEW |
| (Empty) | |
| 1 # Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 |
| 6 class Function(object): |
| 7 """Base class for mathematical functions. |
| 8 |
| 9 The ``callable`` interface is sufficient for when you only ever need to |
| 10 invoke a function. But many times we want to have more information about |
| 11 the function, such as getting its domain or range or knowing whether |
| 12 it's sparse. In addition, we often want to adjust the computational |
| 13 representation of functions (e.g., adding memoization). So this class |
| 14 provides a base class for functions supporting all these sorts of |
| 15 operations in addition to being callable. |
| 16 """ |
| 17 def __init__(self, f): |
| 18 self._f = f |
| 19 |
| 20 def __call__(self, x): |
| 21 return self._f(x) |
| 22 |
| 23 def map(self, g): |
| 24 """Return a new function that applies ``g`` after ``self``. |
| 25 |
| 26 Args: |
| 27 g (callable): the function to post-compose. |
| 28 |
| 29 Returns: |
| 30 An object of the same type as ``self`` which computes ``lambda x: |
| 31 g(self(x))``. N.B., although mathematically we have the equivalence: |
| 32 ``SomeFunction(f).map(g) == SomeFunction(lambda x: g(f(x)))``; |
| 33 operationally the left- and right-hand sides may differ. For |
| 34 example, with the ``MemoizedFunction`` class, the left-hand side |
| 35 will memoize the intermediate ``f(x)`` values whereas the right-hand |
| 36 side will not. |
| 37 """ |
| 38 return self.__class__(lambda x: g(self(x))) |
| 39 |
| 40 |
| 41 class MemoizedFunction(Function): |
| 42 """A function which memoizes its value for all arguments.""" |
| 43 def __init__(self, f): |
| 44 super(MemoizedFunction, self).__init__(f) |
| 45 self._memos = {} |
| 46 |
| 47 def _ClearMemos(self): |
| 48 """Discard all memoized results of this function.""" |
| 49 self._memos = {} |
| 50 |
| 51 def __call__(self, x): |
| 52 try: |
| 53 return self._memos[x] |
| 54 except KeyError: |
| 55 fx = self._f(x) |
| 56 self._memos[x] = fx |
| 57 return fx |
| OLD | NEW |