Skip to content

Commit

Permalink
Implement optional initial value for #86
Browse files Browse the repository at this point in the history
Additionally update package info and have run-tests explicitly use
python 2
  • Loading branch information
EntilZha committed Dec 21, 2016
1 parent 0e2ef32 commit ec17b9e
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 7 deletions.
6 changes: 3 additions & 3 deletions functional/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
from functional.streams import seq, pseq

__author__ = "Pedro Rodriguez"
__copyright__ = "Copyright 2015, Pedro Rodriguez"
__copyright__ = "Copyright 2016, Pedro Rodriguez"
__license__ = "MIT"
__version__ = "0.5.0"
__version__ = "0.8.0"
__maintainer__ = "Pedro Rodriguez"
__email__ = "[email protected]"
__status__ = "Development"
__status__ = "Production"
12 changes: 9 additions & 3 deletions functional/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -874,17 +874,23 @@ def reduce_by_key(self, func):
"""
return self._transform(transformations.reduce_by_key_t(func))

def reduce(self, func):
def reduce(self, func, *initial):
"""
Reduce sequence of elements using func.
Reduce sequence of elements using func. API mirrors functools.reduce
>>> seq([1, 2, 3]).reduce(lambda x, y: x + y)
6
:param func: two parameter, associative reduce function
:param initial: single optional argument acting as initial value
:return: reduced value using func
"""
return _wrap(reduce(func, self))
if len(initial) == 0:
return _wrap(reduce(func, self))
elif len(initial) == 1:
return _wrap(reduce(func, self, initial[0]))
else:
raise ValueError('reduce takes exactly one optional parameter for initial value')

def make_string(self, separator):
"""
Expand Down
8 changes: 8 additions & 0 deletions functional/test/test_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,14 @@ def test_reduce(self):
s = self.seq(l)
self.assertEqual(expect, s.reduce(f))

with self.assertRaises(TypeError):
seq([]).reduce(f)
with self.assertRaises(ValueError):
seq([]).reduce(f, 0, 0)

self.assertEqual(seq([]).reduce(f, 1), 1)
self.assertEqual(seq([0, 2]).reduce(f, 1), 3)

def test_aggregate(self):
f = lambda current, next_element: current + next_element
l = self.seq([1, 2, 3, 4])
Expand Down
2 changes: 1 addition & 1 deletion run-tests.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
echo "Running Python 2 Tests"
python -m 'nose' --with-coverage --cover-package=functional --cover-erase
python2 -m 'nose' --with-coverage --cover-package=functional --cover-erase
sleep 1
echo "Running Python 3 Tests"
python3 -m 'nose' --with-coverage --cover-package=functional --cover-erase
Expand Down

0 comments on commit ec17b9e

Please sign in to comment.