Make a tuple of arbitrary size functionally in Julia
Asked Answered
Y

1

5

An ordinary way to make a tuple in Julia is like this:

n = 5
t2 = (n,n) # t2 = (5,5)
t3 = (n,n,n)# t3 = (5,5,5)

I want to make a tuple of arbitrary size functionally.

n = 5
someFunction(n,size) = ???

t10 = someFunction(n,10) # t10 = (5,5,5,5,5,5,5,5,5,5) 

How can I realize this?

Any information would be appreciated.

Yiyid answered 15/12, 2021 at 13:49 Comment(0)
D
10

Maybe what you are looking for is ntuple ?

julia> ntuple(_ -> 5, 10)
(5, 5, 5, 5, 5, 5, 5, 5, 5, 5)

Note that, you can also use tuple or Tuple:

julia> tuple((5 for _ in 1:10)...)
(5, 5, 5, 5, 5, 5, 5, 5, 5, 5)

julia> Tuple(5 for _ in 1:10)
(5, 5, 5, 5, 5, 5, 5, 5, 5, 5)
Demonology answered 15/12, 2021 at 14:15 Comment(1)
Note that ntuple can take a method argument's type parameter as its length to become a type-stable call, e.g. f(e, a::Val{X}) where {X} = ntuple(_ -> e, X) results in a type-stable f( 10, Val(3) ). The other ways don't have this benefit; the compiler can't figure out that the comprehension (e for _ in 1:X) and the resulting Tuple must have a fixed length X.Neuter

© 2022 - 2024 — McMap. All rights reserved.