Skip to content

Commit

Permalink
Merge pull request #21697 from alyst/fix_ntuple_val
Browse files Browse the repository at this point in the history
Make ntuple(f, n) and ntuple(f, Val{n}) throw ArgumentError when n < 0
  • Loading branch information
Sacha0 authored May 13, 2017
2 parents a898a50 + fc90413 commit b51b42e
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ Breaking changes

This section lists changes that do not have deprecation warnings.

* `ntuple(f, n::Integer)` throws `ArgumentError` if `n` is negative.
Previously an empty tuple was returned ([#21697]).

Library improvements
--------------------
Expand Down
9 changes: 7 additions & 2 deletions base/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ julia> ntuple(i -> 2*i, 4)
```
"""
function ntuple(f::F, n::Integer) where F
t = n <= 0 ? () :
t = n == 0 ? () :
n == 1 ? (f(1),) :
n == 2 ? (f(1), f(2)) :
n == 3 ? (f(1), f(2), f(3)) :
Expand All @@ -120,7 +120,11 @@ function ntuple(f::F, n::Integer) where F
return t
end

_ntuple(f, n) = (@_noinline_meta; ([f(i) for i = 1:n]...))
function _ntuple(f, n)
@_noinline_meta
(n >= 0) || throw(ArgumentError(string("tuple length should be ≥0, got ", n)))
([f(i) for i = 1:n]...)
end

# inferrable ntuple
ntuple(f, ::Type{Val{0}}) = (@_inline_meta; ())
Expand All @@ -142,6 +146,7 @@ ntuple(f, ::Type{Val{15}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6)

function ntuple(f::F, ::Type{Val{N}}) where {F,N}
Core.typeassert(N, Int)
(N >= 0) || throw(ArgumentError(string("tuple length should be ≥0, got ", N)))
_ntuple((), f, Val{N})
end

Expand Down
4 changes: 4 additions & 0 deletions test/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ end
@test @inferred(ntuple(abs2, Val{4})) == (1, 4, 9, 16)
@test @inferred(ntuple(abs2, Val{5})) == (1, 4, 9, 16, 25)
@test @inferred(ntuple(abs2, Val{6})) == (1, 4, 9, 16, 25, 36)
# issue #21697
@test_throws ArgumentError ntuple(abs2, Val{-1})

# issue #12854
@test_throws TypeError ntuple(identity, Val{1:2})
Expand All @@ -179,6 +181,8 @@ for n = 0:20
@test t[i] == i
end
end
# issue #21697
@test_throws ArgumentError ntuple(identity, -1)

# issue #19719
@test_throws BoundsError (1,2,3)[falses(4)]
Expand Down

0 comments on commit b51b42e

Please sign in to comment.