Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Initial commit.

  • Loading branch information...
commit 0dc1e95c3fffbc44e2875b900706ffc69bffcbd7 1 parent 4a40303
@sdiehl authored
View
32 README.md
@@ -1,4 +1,34 @@
opcurry
=======
-Curried versions of Python operator module.
+Curried versions of Python operator module.
+
+Usage
+
+```python
+>>> import opcurry
+
+>>> f = opcurry.add(1)
+>>> f(2) == 3
+>>> f(3) == 4
+
+>>> opcurry.neg(1)
+-1
+
+>>> h = opcurry.and_(True)
+>>> h(True)
+True
+>>> h(False)
+False
+
+>>> from opcurry import mul, add, xor
+
+>>> map(add(1), [2,3,4])
+[3, 4, 5]
+
+>>> map(mul(3), [2,3,4])
+[6, 9, 12]
+
+>>> print xor(2)
+xor 2
+```
View
1  opcurry/__init__.py
@@ -0,0 +1 @@
+from curried import *
View
54 opcurry/curried.py
@@ -0,0 +1,54 @@
+import operator
+from copy import deepcopy
+from inspect import isbuiltin, getmembers
+
+__all__ = []
+
+def cfunc_nargs(obj):
+ docstr = obj.__doc__
+
+ if docstr:
+ items = docstr.split('\n')
+ if items:
+ func_descr = items[0]
+ s = func_descr.replace(obj.__name__,'')
+ idx1 = s.find('(')
+ idx2 = s.find(')',idx1)
+ if idx1 != -1 and idx2 != -1 and (idx2>idx1+1):
+ return len(s[idx1+1:idx2].split(','))
+
+class curry(object):
+
+ def __new__(cls, *args):
+ if len(args) == cls.nargs:
+ return cls.callsite(*args)
+ else:
+ return object.__new__(cls, *args)
+
+ def __init__(self, *args):
+ self.args = args
+
+ def __call__(self, *args):
+ targs = self.args + args
+ if len(targs) > self.nargs:
+ raise TypeError("Too many arguments.")
+ elif len(targs) == self.nargs:
+ return self.callsite(*targs)
+ else:
+ nw = deepcopy(self)
+ nw.args = targs
+ return nw
+
+ def __repr__(self):
+ return '%s %s' % (self.callsite.__name__, ' '.join(map(repr,self.args)))
+
+for name, op in getmembers(operator):
+ if isbuiltin(op):
+ name = op.__name__
+ nargs = cfunc_nargs(op)
+ globals()[name] = type(name, (curry,), {
+ 'callsite' : op,
+ 'name' : name,
+ 'nargs' : nargs
+ })
+ __all__.append(name)
View
13 setup.py
@@ -0,0 +1,13 @@
+#!/usr/bin/env python
+from setuptools import setup, find_packages
+
+setup(
+ name='opcurry',
+ version='0.1.0',
+ author='Stephen Diehl',
+ author_email='stephen.m.diehl@gmail.com',
+ description='Curried operators',
+ packages=find_packages(),
+ install_requires=[''],
+ data_files=[]
+)
View
BIN  tests/.tests.py.swp
Binary file not shown
View
20 tests/tests.py
@@ -0,0 +1,20 @@
+import opcurry
+
+f = opcurry.add(1)
+assert f(2) == 3
+assert f(3) == 4
+
+g = opcurry.neg(1)
+assert g == -1
+
+h = opcurry.mul(2,3)
+assert h == 6
+
+i = opcurry.and_(True)
+assert i(True) == True
+
+assert map(opcurry.add(1), xrange(5)) == [1,2,3,4,5]
+
+assert map(opcurry.mul(3), [2,3,4]) == [6,9,12]
+
+assert repr(opcurry.xor(2)) == "xor 2"
Please sign in to comment.
Something went wrong with that request. Please try again.