From 31975bfa4e628ea1724adb708714d0cddf4593e3 Mon Sep 17 00:00:00 2001 From: Alexey Stukalov Date: Thu, 4 May 2017 21:19:07 +0200 Subject: [PATCH] ntuple(f, -1) throws ArgumentError --- NEWS.md | 3 +++ base/tuple.jl | 8 ++++++-- test/tuple.jl | 2 ++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/NEWS.md b/NEWS.md index 7c1418f258cd27..2857ade5692b9f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -12,6 +12,9 @@ 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 -------------------- diff --git a/base/tuple.jl b/base/tuple.jl index 4c7687f5a52be7..dc041a47937fb6 100644 --- a/base/tuple.jl +++ b/base/tuple.jl @@ -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)) : @@ -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; ()) diff --git a/test/tuple.jl b/test/tuple.jl index d59b0497cdc9f8..2385e52a9ef4fa 100644 --- a/test/tuple.jl +++ b/test/tuple.jl @@ -181,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)]