Skip to content

Commit 85429ee

Browse files
committed
More methods that can be faster than Base
1 parent 23a3863 commit 85429ee

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/TupleTools.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,24 @@ look as (t[1:i-1]..., t2..., t[i+1:end]). Note that element `t[i]` is deleted. U
107107
@inline _insertat(t::Tuple, i::Int, t2::Tuple) = i == 1 ? (t2..., tail(t)...) : (t[1], _insertat(tail(t), i-1, t2)...)
108108
@inline _insertat(t::Tuple{}, i::Int, t2::Tuple) = throw(BoundsError(t, i))
109109

110+
"""
111+
sum(t::Tuple)
112+
113+
Returns the sum of the element of a tuple, or `0` for an empty tuple.
114+
"""
115+
@inline sum(t::Tuple{}) = 0
116+
@inline sum(t::Tuple{Any}) = t[1]
117+
@inline sum(t::Tuple) = t[1]+sum(tail(t))
118+
119+
"""
120+
prod(t::Tuple)
121+
122+
Returns the product of the elements of a tuple, or `1` for an empty tuple.
123+
"""
124+
@inline prod(t::Tuple{}) = 1
125+
@inline prod(t::Tuple{Any}) = t[1]
126+
@inline prod(t::Tuple) = t[1]*prod(tail(t))
127+
110128
"""
111129
minimum(t::Tuple)
112130

test/runtests.jl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,15 @@ i = rand(1:n)
2828
@test @inferred(TupleTools.insertat(t, i, (1,2,3))) == (vcat(p[1:i-1], [1,2,3], p[i+1:n])...)
2929
@test @inferred(TupleTools.vcat((1,2,3),4,(5,),(),(6,7,8))) == (1,2,3,4,5,6,7,8)
3030

31+
@test @inferred(TupleTools.sum(t)) == sum(t)
32+
@test @inferred(TupleTools.prod(t)) == prod(t)
33+
3134
@test @inferred(TupleTools.findmin(t)) == findmin(t)
3235
@test @inferred(TupleTools.findmax(t)) == findmax(t)
3336
@test @inferred(TupleTools.minimum(t)) == minimum(t)
3437
@test @inferred(TupleTools.maximum(t)) == maximum(t)
3538
@test @inferred(TupleTools.indmin(t)) == indmin(t)
36-
@test @inferred(TupleTools.indmax(t)) == indmin(t)
39+
@test @inferred(TupleTools.indmax(t)) == indmax(t)
3740

3841
@test @inferred(TupleTools.sort(t; rev = true)) == (sort(p; rev = true)...)
3942
@test @inferred(TupleTools.sortperm(t)) == (sortperm(p)...)

0 commit comments

Comments
 (0)