ntuple
ntuple(f::Function, n)
Create a tuple of length n
, computing each element as f(i)
, where i
is the index of the element.
Examples
-
Create a tuple of squared numbers:
julia> ntuple(x -> x^2, 5) (1, 4, 9, 16, 25)
This example creates a tuple of length 5 where each element is computed as the square of its index.
-
Generate a tuple of strings using a custom function:
julia> ntuple(i -> "Element $i", 3) ("Element 1", "Element 2", "Element 3")
It generates a tuple of length 3 where each element is computed using a custom function that takes the index and returns a string.
- Use an anonymous function to create a tuple of exponential values:
julia> ntuple(i -> 2.0^i, 4) (1.0, 2.0, 4.0, 8.0)
In this example, an anonymous function is used to compute the elements of the tuple as exponential values of 2.
Common mistake example:
julia> ntuple(x -> x^2, -2)
ERROR: ArgumentError: ntuple: n must be nonnegative
In this example, a negative value is provided as the length of the tuple. The ntuple
function expects a nonnegative value for n
. To avoid such errors, ensure that n
is a nonnegative integer before using ntuple
.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.