Skip to content

Commit a898092

Browse files
jebejJutho
authored andcommitted
Add cumsum and cumprod methods (#2)
* Add cumsum and cumprod methods * test for cumsum and cumprod * cumsum and cumprod docs
1 parent 9ae0752 commit a898092

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

docs/src/index.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@ TupleTools.vcat
4040
```
4141
```@docs
4242
TupleTools.sum
43+
TupleTools.cumsum
4344
TupleTools.prod
45+
TupleTools.cumprod
4446
```
4547

4648
```@docs

src/TupleTools.jl

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ module TupleTools
33

44
using Base: tuple_type_head, tuple_type_tail, tuple_type_cons, tail, front, setindex
55
# import Base: permute # TODO: this can disappear when Sparse moves out of Base
6+
import Base: cumsum, cumprod
67

78
"""
89
struct StaticLength{N} end
@@ -114,6 +115,18 @@ Returns the sum of the element of a tuple, or `0` for an empty tuple.
114115
@inline sum(t::Tuple{Any}) = t[1]
115116
@inline sum(t::Tuple) = t[1]+sum(tail(t))
116117

118+
"""
119+
cumsum(t::Tuple)
120+
121+
Returns the cumulative sum of the elements of a tuple, or `()` for an empty tuple.
122+
"""
123+
function cumsum(t::Tuple)
124+
t_1, t_tail = first(t), tail(t)
125+
return (t_1,cumsum((t_1+first(t_tail),tail(t_tail)...))...)
126+
end
127+
cumsum(t::Tuple{Any}) = t
128+
cumsum(t::Tuple{}) = t
129+
117130
"""
118131
prod(t::Tuple)
119132
@@ -123,6 +136,18 @@ Returns the product of the elements of a tuple, or `1` for an empty tuple.
123136
@inline prod(t::Tuple{Any}) = t[1]
124137
@inline prod(t::Tuple) = t[1]*prod(tail(t))
125138

139+
"""
140+
cumprod(t::Tuple)
141+
142+
Returns the cumulative product of the elements of a tuple, or `()` for an empty tuple.
143+
"""
144+
function cumprod(t::Tuple)
145+
t_1, t_tail = first(t), tail(t)
146+
return (t_1,cumprod((t_1*first(t_tail),tail(t_tail)...))...)
147+
end
148+
cumprod(t::Tuple{Any}) = t
149+
cumprod(t::Tuple{}) = t
150+
126151
"""
127152
minimum(t::Tuple)
128153

test/runtests.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ i = rand(1:n)
3636
@test @inferred(TupleTools.vcat((1,2,3),4,(5,),(),(6,7,8))) == (1,2,3,4,5,6,7,8)
3737

3838
@test @inferred(TupleTools.sum(t)) == sum(t)
39+
@test @inferred(TupleTools.cumsum(t)) == (cumsum(p)...,)
3940
@test @inferred(TupleTools.prod(t)) == prod(t)
41+
@test @inferred(TupleTools.cumprod(t)) == (cumprod(p)...,)
4042

4143
@test @inferred(TupleTools.findmin(t)) == findmin(t)
4244
@test @inferred(TupleTools.findmax(t)) == findmax(t)

0 commit comments

Comments
 (0)