Skip to content

Commit

Permalink
Merge pull request #12 from adrian17/new-functions
Browse files Browse the repository at this point in the history
implemented init, inits, tails; added docstrings
  • Loading branch information
EntilZha committed Mar 12, 2015
2 parents 8b67adc + 793d875 commit f23ce0c
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
48 changes: 48 additions & 0 deletions functional/chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,59 @@ def head_option(self):
return self.head()

def last(self):
"""
Returns the last element of the sequence.
>>> seq([1, 2, 3]).last()
3
Raises IndexError when the sequence is empty.
>>> seq([]).last()
Traceback (most recent call last):
...
IndexError: list index out of range
"""
return _wrap(self.sequence[-1])

def init(self):
"""
Returns the sequence, without its last element.
>>> seq([1, 2, 3]).init()
[1, 2]
"""
return FunctionalSequence(self.sequence[:-1])

def tail(self):
"""
Returns the sequence, without its first element.
>>> seq([1, 2, 3]).init()
[2, 3]
"""
return FunctionalSequence(self.sequence[1:])

def inits(self):
"""
Returns consecutive inits of the sequence.
>>> seq([1, 2, 3]).inits()
[[1, 2, 3], [1, 2], [1], []]
"""
result = [_wrap(self.sequence[:i]) for i in reversed(range(len(self.sequence)+1))]
return FunctionalSequence(result)

def tails(self):
"""
Returns consecutive tails of the sequence.
>>> seq([1, 2, 3]).tails()
[[1, 2, 3], [2, 3], [3], []]
"""
result = [_wrap(self.sequence[i:]) for i in range(len(self.sequence)+1)]
return FunctionalSequence(result)

def drop(self, n):
return FunctionalSequence(self.sequence[n:])

Expand Down
17 changes: 17 additions & 0 deletions test/test_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,28 @@ def test_last(self):
self.assertEqual(l.last(), [3, 4])
self.assertType(l.last())

def test_init(self):
l = seq([1, 2, 3, 4])
expect = [1, 2, 3]
self.assertSequenceEqual(l.init(), expect)

def test_tail(self):
l = seq([1, 2, 3, 4])
expect = [2, 3, 4]
self.assertSequenceEqual(l.tail(), expect)

def test_inits(self):
l = seq([1, 2, 3])
expect = [[1, 2, 3], [1, 2], [1], []]
self.assertSequenceEqual(l.inits(), expect)
self.assertEquals(l.inits().map(lambda s: s.sum()), [6, 3, 1, 0])

def test_tails(self):
l = seq([1, 2, 3])
expect = [[1, 2, 3], [2, 3], [3], []]
self.assertSequenceEqual(l.tails(), expect)
self.assertEquals(l.tails().map(lambda s: s.sum()), [6, 5, 3, 0])

def test_drop(self):
l = [1, 2, 3, 4, 5, 6]
expect = [5, 6]
Expand Down

0 comments on commit f23ce0c

Please sign in to comment.