Skip to content

Commit 64be4ee

Browse files
committed
Merge pull request #15578 from JuliaLang/teh/lispy_ntuple
Inferrable ntuple without generated functions
2 parents c45175f + 7f62112 commit 64be4ee

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

base/tuple.jl

+11-13
Original file line numberDiff line numberDiff line change
@@ -50,19 +50,17 @@ ntuple(f::Function, n::Integer) =
5050
n==5 ? (f(1),f(2),f(3),f(4),f(5),) :
5151
tuple(ntuple(f,n-5)..., f(n-4), f(n-3), f(n-2), f(n-1), f(n))
5252

53-
ntuple(f, ::Type{Val{0}}) = ()
54-
ntuple(f, ::Type{Val{1}}) = (f(1),)
55-
ntuple(f, ::Type{Val{2}}) = (f(1),f(2))
56-
ntuple(f, ::Type{Val{3}}) = (f(1),f(2),f(3))
57-
ntuple(f, ::Type{Val{4}}) = (f(1),f(2),f(3),f(4))
58-
ntuple(f, ::Type{Val{5}}) = (f(1),f(2),f(3),f(4),f(5))
59-
@generated function ntuple{N}(f, ::Type{Val{N}})
60-
if !isa(N,Int)
61-
:(throw(TypeError(:ntuple, "", Int, $(QuoteNode(N)))))
62-
else
63-
M = N-5
64-
:(tuple(ntuple(f, Val{$M})..., f($N-4), f($N-3), f($N-2), f($N-1), f($N)))
65-
end
53+
# inferrable ntuple
54+
function ntuple{F,N}(f::F, ::Type{Val{N}})
55+
Core.typeassert(N, Int)
56+
_ntuple((), f, Val{N})
57+
end
58+
59+
# Build up the output until it has length N
60+
_ntuple{F,N}(out::NTuple{N}, f::F, ::Type{Val{N}}) = out
61+
function _ntuple{F,N,M}(out::NTuple{M}, f::F, ::Type{Val{N}})
62+
@_inline_meta
63+
_ntuple((out..., f(M+1)), f, Val{N})
6664
end
6765

6866
# 0 argument function

0 commit comments

Comments
 (0)