├── .gitignore ├── LICENSE ├── README.md ├── guac ├── __init__.py ├── functions.py ├── instances.py └── monad.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | # Byte-compiled / optimized / DLL files 3 | __pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | env/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # IPython Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # dotenv 80 | .env 81 | 82 | # virtualenv 83 | venv/ 84 | ENV/ 85 | 86 | # Spyder project settings 87 | .spyderproject 88 | 89 | # Rope project settings 90 | .ropeproject 91 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Jaden Geller 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Guac 2 | 3 | Guac is a package that provides monadic [do-notation](https://en.wikibooks.org/wiki/Haskell/do_notation), 4 | inspired by Haskell, in Python. [Monads](http://blog.plover.com/prog/burritos.html) provide 5 | "programmable semicolons" by which the behavior of programs can be changed. A common, useful monad is the 6 | list monad, which represents non-deterministic computations. The list monad makes it very easy to write 7 | backtracking searches. 8 | 9 | ## Example 10 | 11 | Here's an example that computes all the possible ways you can give $0.27 change with pennies, nickels, dimes, 12 | and quarters: 13 | 14 | ```python 15 | from guac import * 16 | 17 | @monadic(ListMonad) 18 | def make_change(amount_still_owed, possible_coins): 19 | change = [] 20 | 21 | # Keep adding coins while we owe them money and there are still coins. 22 | while amount_still_owed > 0 and possible_coins: 23 | 24 | # "Nondeterministically" choose whether to give another coin of this value. 25 | # Aka, try both branches, and return both results. 26 | give_min_coin = yield [True, False] 27 | 28 | if give_min_coin: 29 | # Give coin 30 | min_coin = possible_coins[0] 31 | change.append(min_coin) 32 | amount_still_owed -= min_coin 33 | else: 34 | # Never give this coin value again (in this branch!) 35 | del possible_coins[0] 36 | 37 | # Did we charge them the right amount? 38 | yield guard(amount_still_owed == 0) 39 | 40 | # Lift the result back into the monad. 41 | yield lift(change) 42 | 43 | print(make_change(27, [1, 5, 10, 25])) 44 | ``` 45 | 46 | Running this program will print a list of lists, each list containing a different set of numbers 47 | that add up to 27. You can imagine lots of cool ways this could be used, from unification to parsing! 48 | 49 | If you have ever used Python's [asyncio](https://docs.python.org/3/library/asyncio.html) package, this may feel 50 | familiar. That's because asyncio is actually a monad! Of course, they don't formalize it as such, but it could 51 | be implemented as one, and it uses coroutines in the exact same way. Unlike asyncio, which simply continues 52 | computation when a result is available, this library makes it possible to repeat computation from arbitrary 53 | yields in the coroutine. 54 | 55 | ## Building Your Own Monads 56 | 57 | Guac comes with a few simple monads, but it's super easy to implement your own monad. You don't need to worry 58 | about any of the coroutine logic---Guac handles that for you. You just have to implement two simple 59 | functions, `lift` and `bind`: 60 | 61 | ```python 62 | class ListMonad(Monad): 63 | @staticmethod 64 | def lift(x): 65 | return [x] 66 | 67 | @staticmethod 68 | def bind(m, f): 69 | result = [] 70 | for elem in m: 71 | result += f(elem) 72 | return result 73 | ``` 74 | 75 | Your definitions should ideally follow the [monad laws](https://wiki.haskell.org/Monad_laws), though the 76 | lack of types can make this a bit janky to reason about. 77 | 78 | ## Unspecialized Monadic Computations 79 | 80 | You might have noticed that you use the `@monadic` decorated to turn a coroutine into a function that runs the 81 | monad. To specialize a compuation to a specific monad instance, you pass that instance as an argument to the 82 | decorator. Otherwise, you create an unspecialized monadic computation that will inherit its instance from 83 | the caller. 84 | 85 | Here's the implementation of the `guard` function used above: 86 | ```python 87 | @monadic 88 | def guard(condition): 89 | if condition: 90 | yield unit() 91 | else: 92 | yield empty() 93 | ``` 94 | 95 | Handy helper functions like `unit` and `empty` are defined by Guac. Some functions require a little bit 96 | more than a monad. For example, `empty` must be implemented in addition to `lift` and `bind` on your monad 97 | class to use these functions. 98 | 99 | ## Usage 100 | 101 | ### Requirements 102 | 103 | Guac requires an implementation of Python 3 that supports `copy.deepcopy` on generator functions. The most 104 | common distribution, CPython, is lacking this feature, but [pypy](http://pypy.org) implements it! 105 | 106 | ### Installation 107 | 108 | If you already have the pypy distribution of Python 3, you can install this package with pip: 109 | ``` 110 | pypy3 -m pip install guac 111 | ``` 112 | If you don't yet have pypy, you can download and install it [here](http://pypy.org/download.html). Alternatively, 113 | if you have Homebrew on macOS, you can run this: 114 | ``` 115 | brew install pypy3 116 | ``` 117 | -------------------------------------------------------------------------------- /guac/__init__.py: -------------------------------------------------------------------------------- 1 | from .monad import * 2 | from .instances import * 3 | from .functions import * 4 | -------------------------------------------------------------------------------- /guac/functions.py: -------------------------------------------------------------------------------- 1 | from .monad import * 2 | 3 | @monadic 4 | def bind(m, f): 5 | """ 6 | Unwraps the plain value from the monadic context and 7 | feeds it into the function, yielding a monadic value. 8 | 9 | Arguments: 10 | m -- the monadic value 11 | f -- the function from plain value to monadic value 12 | """ 13 | 14 | yield f(m) 15 | 16 | @monadic 17 | def lift(value): 18 | """ 19 | Lifts a plain value into the monadic context. 20 | 21 | Arguments: 22 | x - the plain value to lift 23 | """ 24 | 25 | yield Monad._Builtin(lambda m: m.lift(value)) 26 | 27 | @monadic 28 | def empty(): 29 | """ 30 | Creates an empty monadic context. 31 | 32 | Note that this function is not required to be implemented 33 | by all monads. 34 | """ 35 | 36 | yield Monad._Builtin(lambda m: m.empty()) 37 | 38 | @monadic 39 | def concat(x, y): 40 | """ 41 | Concatenates two monadic context. 42 | 43 | Note that this function is not required to be implemented 44 | by all monads. 45 | """ 46 | 47 | yield Monad._Builtin(lambda m: m.concat(x, y)) 48 | 49 | @monadic 50 | def unit(): 51 | """ 52 | Lifts a unit value into the monadic context. 53 | """ 54 | 55 | yield lift(()) 56 | 57 | @monadic 58 | def guard(condition): 59 | """ 60 | Guards against a condition within a monadic context, trimming 61 | branches where this condition does not hold. 62 | 63 | Requires the monad to support `empty`. 64 | 65 | Argument: 66 | condition -- the condition that must hold 67 | """ 68 | 69 | if condition: 70 | yield unit() 71 | else: 72 | yield empty() 73 | 74 | @monadic 75 | def map(f, m): 76 | """ 77 | Maps the transform over the plain value within the monadic context. 78 | 79 | Argument: 80 | f -- function that maps from plain value to plain value 81 | m -- the monadic value to be mapped over 82 | """ 83 | 84 | x = yield m 85 | yield lift(f(x)) 86 | 87 | @monadic 88 | def join(m): 89 | """ 90 | Flattens a layer of nesting of monadic context. 91 | 92 | Argument: 93 | m -- a monadic value nested in a monadic value 94 | """ 95 | 96 | x = yield m 97 | yield x 98 | 99 | @monadic 100 | def filter(predicate, m): 101 | """ 102 | Filters out values where the condition does not hold. 103 | 104 | Requires the monad to support `empty`. 105 | 106 | Argument: 107 | predicate -- a bool-returning function over plain values 108 | m -- the monadic value to filter 109 | """ 110 | 111 | x = yield m 112 | guard(pred(x)) 113 | yield x 114 | -------------------------------------------------------------------------------- /guac/instances.py: -------------------------------------------------------------------------------- 1 | from .monad import * 2 | 3 | class ListMonad(Monad): 4 | """ 5 | Monad instance for non-deterministic computation 6 | using lists. 7 | """ 8 | 9 | @staticmethod 10 | def lift(x): 11 | """ 12 | Lifts a value into a singleton list. 13 | 14 | Arguments: 15 | x -- the plain value to lift 16 | """ 17 | 18 | return [x] 19 | 20 | @staticmethod 21 | def bind(m, f): 22 | """ 23 | Performs a flat-map operation over a list. 24 | 25 | Arguments: 26 | m -- the list to map over 27 | f -- a function from list element to list 28 | """ 29 | 30 | result = [] 31 | for elem in m: 32 | result += f(elem) 33 | return result 34 | 35 | @staticmethod 36 | def empty(): 37 | """ 38 | Constructs an empty list. 39 | """ 40 | 41 | return [] 42 | 43 | @staticmethod 44 | def concat(x, y): 45 | """ 46 | Concatenates two lists. 47 | 48 | Arguments: 49 | x -- the list to order first 50 | y -- the list to order second 51 | """ 52 | 53 | return x + y 54 | 55 | class NoneMonad(Monad): 56 | """ 57 | Monad instance for failable computation using None. 58 | """ 59 | 60 | @staticmethod 61 | def lift(x): 62 | """ 63 | Does nothing. 64 | 65 | Since we're not wrapping the non-None case, 66 | we don't need more than an identity function here. 67 | 68 | Arguments: 69 | x -- the value to return 70 | """ 71 | 72 | return x 73 | 74 | @staticmethod 75 | def bind(m, f): 76 | """ 77 | Performs the operation on the value if it is not None. 78 | 79 | Arguments: 80 | m -- the value to operate on 81 | f -- a transform that may return None 82 | """ 83 | 84 | if m is not None: 85 | return f(m) 86 | else: 87 | return None 88 | 89 | @staticmethod 90 | def empty(): 91 | """ 92 | Constructs the value None. 93 | """ 94 | 95 | return None 96 | 97 | @staticmethod 98 | def concat(x, y): 99 | """ 100 | Returns the first value that is not None, 101 | else returns None. 102 | 103 | Arguments: 104 | x -- the first value 105 | y -- the second value 106 | """ 107 | return x or y 108 | 109 | class ExceptionMonad(Monad): 110 | """ 111 | Monad instance for failable computation using Exception. 112 | """ 113 | 114 | @staticmethod 115 | def lift(x): 116 | """ 117 | Does nothing. 118 | 119 | Since we're not wrapping the non-Exception case, 120 | we don't need more than an identity function here. 121 | 122 | Arguments: 123 | x -- the value to return 124 | """ 125 | 126 | return x 127 | 128 | @staticmethod 129 | def bind(m, f): 130 | """ 131 | Performs the operation on the value if it is not an 132 | Exception. 133 | 134 | Arguments: 135 | m -- the value to operate on 136 | f -- a transform that may return an Exception 137 | """ 138 | 139 | if m is not None: 140 | return f(m) 141 | else: 142 | return None 143 | 144 | @staticmethod 145 | def empty(): 146 | """ 147 | Constructs an empty Exception. 148 | """ 149 | 150 | return Exception() 151 | 152 | @staticmethod 153 | def concat(x, y): 154 | """ 155 | Returns the first value that is not an Exception, 156 | else returns the last Exception. 157 | 158 | Arguments: 159 | x -- the first value 160 | y -- the second value 161 | """ 162 | if not isinstance(x, Exception): 163 | return x 164 | else: 165 | return y 166 | 167 | class FunctionMonad(Monad): 168 | """ 169 | Monad instance for functions. 170 | """ 171 | 172 | @staticmethod 173 | def lift(x): 174 | """ 175 | Lifts the value into a constant function that always returns `x` 176 | regardless of its input. 177 | 178 | Arguments: 179 | x -- the value to always return from the function 180 | """ 181 | return lambda _: x 182 | 183 | @staticmethod 184 | def bind(m, f): 185 | """ 186 | Returns a function that feeds its argument into the function that 187 | results from feeing its argument into the monadic function and 188 | then feeding that function into the transform function. 189 | 190 | Arguments: 191 | m -- the monadic function 192 | f -- the transform function 193 | """ 194 | return lambda x: f(m(x))(x) 195 | 196 | class StateMonad(Monad): 197 | """ 198 | Monad instance that threads state through a computation. 199 | 200 | Stateful computations are functions from state to 201 | result-new state tuples. 202 | """ 203 | 204 | @staticmethod 205 | def lift(x): 206 | """ 207 | Lifts the value into a state tuple. 208 | """ 209 | return lambda state: (x, state) 210 | 211 | @staticmethod 212 | def bind(m, f): 213 | """ 214 | Extracts the result of running the stateful computation 215 | and passing it into the transform while threading the state 216 | through. 217 | 218 | Arguments: 219 | m -- the stateful computation 220 | f -- a function from plain value to stateful computation 221 | """ 222 | def thread_state(state): 223 | (x, new_state) = m(state) 224 | return f(x)(new_state) 225 | return thread_state 226 | 227 | -------------------------------------------------------------------------------- /guac/monad.py: -------------------------------------------------------------------------------- 1 | import abc, copy, inspect 2 | 3 | class Monad(metaclass=abc.ABCMeta): 4 | """An abstract class whose subclasses represent monad instances.""" 5 | 6 | @staticmethod 7 | @abc.abstractmethod 8 | def lift(x): 9 | """ 10 | Lifts a plain value into the monadic context. 11 | 12 | Arguments: 13 | x - the plain value to lift 14 | """ 15 | return NotImplemented 16 | 17 | @staticmethod 18 | @abc.abstractmethod 19 | def bind(m, f): 20 | """ 21 | Unwraps the plain value from the monadic context and 22 | feeds it into the function, yielding a monadic value. 23 | 24 | Arguments: 25 | m -- the monadic value 26 | f -- the function from plain value to monadic value 27 | """ 28 | return NotImplemented 29 | 30 | class _Builtin: 31 | def __init__(self, impl): 32 | self.evaluate_in_monad = impl 33 | 34 | @classmethod 35 | def _run(self, computation): 36 | def step(monadic_value, continuation): 37 | if isinstance(monadic_value, Monad._Builtin): 38 | monadic_value = monadic_value.evaluate_in_monad(self) 39 | def proceed(x): 40 | invocation = copy.deepcopy(continuation) # Requires Pypy! 41 | try: 42 | return step(invocation.send(x), invocation) 43 | except StopIteration as e: 44 | if e.value: 45 | raise ValueError("unexpected return value in monadic function") 46 | return self.lift(x) 47 | return self.bind(monadic_value, proceed) 48 | try: 49 | return step(next(computation), computation) 50 | except StopIteration as e: 51 | raise ValueError("monadic function must yield at least once") 52 | 53 | # + Decorator for executing a monad 54 | # - an argument may be specified to specialize for a specific monad 55 | # - otherwise, the monad may be specialized by named arg at callsite 56 | # - yield correpsonds to the bind operator in that it "unpacks" a value 57 | # - execution of the monadic effects end at last yield before return 58 | def monadic(instance): 59 | """ 60 | Decorates a monadic function so that invocation runs the monad. 61 | 62 | If no instance argument is supplied, the function may only be 63 | invoked from other monadic functions. In these cases, the instance 64 | argument will be inherited from the caller. 65 | 66 | Arguments: 67 | instance -- an optional argument specializing the monad instance 68 | 69 | Usage: 70 | Within the decorated function, use `yield` to perform a bind operation 71 | on a monadic value. The value to be yielded is that monadic value to 72 | bind. The result of the yield will be the unwrapped mondic value. 73 | The function must end with a yield of the resulting value after the 74 | desired transforms have been applied. 75 | 76 | Example: 77 | @monadic(ListMonad) 78 | def make_change(amount_still_owed, possible_coins): 79 | change = [] 80 | while amount_still_owed > 0 and possible_coins: 81 | give_min_coin = yield [True, False] # nondeterministic choice 82 | if give_min_coin: 83 | min_coin = possible_coins[0] 84 | change.append(min_coin) 85 | amount_still_owed -= min_coin 86 | else: 87 | del possible_coins[0] 88 | yield guard(amount_still_owed == 0) 89 | yield lift(change) 90 | print(make_change(27, [1, 5, 10, 25])) 91 | """ 92 | def wrap(f, monad=None): 93 | def monadic_context(*args, monad=monad, **kwargs): 94 | if monad is None: #infer from context 95 | for (frame, _, _, name, _, _) in inspect.stack()[1:]: 96 | if name == 'monadic_context': 97 | monad = inspect.getargvalues(frame).locals['monad'] 98 | break 99 | del frame 100 | else: 101 | raise RuntimeError('unspecified monadic context') 102 | return monad._run(f(*args, **kwargs)) 103 | return monadic_context 104 | 105 | if issubclass(instance, Monad): 106 | return lambda f: wrap(f, monad=instance) 107 | elif not callable(instance): 108 | raise TypeError('expected instance of Monad') 109 | 110 | # We weren't given an instance; return an unspecialized wrapper. 111 | f = instance 112 | del instance 113 | 114 | if inspect.isgeneratorfunction(f): 115 | return wrap(f) 116 | else: 117 | raise ValueError('monadic function must be a generator') 118 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup(name='guac', 4 | version='1.0.0', 5 | description='Monadic do-notation in Python', 6 | url='https://github.com/JadenGeller/Guac', 7 | author='Jaden Geller', 8 | license='MIT', 9 | packages=['guac'], 10 | classifiers=['Intended Audience :: Developers', 11 | 'Intended Audience :: Education', 12 | 'Topic :: Software Development :: Libraries', 13 | 'License :: OSI Approved :: MIT License', 14 | 'Programming Language :: Python :: 3 :: Only', 15 | 'Programming Language :: Python :: Implementation :: PyPy' 16 | ], 17 | keywords='monad monadic coroutine generator pypy backtracking', 18 | zip_safe=True) 19 | --------------------------------------------------------------------------------