| OLD | NEW |
| 1 # Copyright 2016 The Chromium Authors. All rights reserved. | 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 | 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
| 4 | 4 |
| 5 | 5 |
| 6 class Function(object): | 6 class Function(object): |
| 7 """Base class for mathematical functions. | 7 """Base class for mathematical functions. |
| 8 | 8 |
| 9 The ``callable`` interface is sufficient for when you only ever need to | 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 | 10 invoke a function. But many times we want to have more information about |
| (...skipping 26 matching lines...) Expand all Loading... |
| 37 """ | 37 """ |
| 38 return self.__class__(lambda x: g(self(x))) | 38 return self.__class__(lambda x: g(self(x))) |
| 39 | 39 |
| 40 | 40 |
| 41 class MemoizedFunction(Function): | 41 class MemoizedFunction(Function): |
| 42 """A function which memoizes its value for all arguments.""" | 42 """A function which memoizes its value for all arguments.""" |
| 43 def __init__(self, f): | 43 def __init__(self, f): |
| 44 super(MemoizedFunction, self).__init__(f) | 44 super(MemoizedFunction, self).__init__(f) |
| 45 self._memos = {} | 45 self._memos = {} |
| 46 | 46 |
| 47 def _ClearMemos(self): | 47 def ClearMemos(self): |
| 48 """Discard all memoized results of this function.""" | 48 """Discard all memoized results of this function.""" |
| 49 self._memos = {} | 49 self._memos = {} |
| 50 | 50 |
| 51 def __call__(self, x): | 51 def __call__(self, x): |
| 52 try: | 52 try: |
| 53 return self._memos[x] | 53 return self._memos[x] |
| 54 except KeyError: | 54 except KeyError: |
| 55 fx = self._f(x) | 55 fx = self._f(x) |
| 56 self._memos[x] = fx | 56 self._memos[x] = fx |
| 57 return fx | 57 return fx |
| OLD | NEW |