I want to run a bit of code for each item in a vector, as if I’d typed it out multiple types. Not using a function or run-time loop. How can I do that?
Similar to this but with no function:
foreach(1:5) do x
println(x)
end
I want to run a bit of code for each item in a vector, as if I’d typed it out multiple types. Not using a function or run-time loop. How can I do that?
Similar to this but with no function:
foreach(1:5) do x
println(x)
end
Use the map command.
v = [1, 2, 3, 4, 5] # example vector with 5 elements
map(x -> x^3, v)
The will cube each element of vector v with the result.
5-element Vector{Int64}:
1
8
27
64
125
This is usually referred to as “unrolling”. You can’t do this in general for vectors in julia because a vector can hold a variable number of items (under some restrictions maybe you can for your use case). It is possible for StaticArrays and Tuples though.
There is https://github.com/cstjean/Unrolled.jl and https://github.com/StephenVavasis/Unroll.jl and maybe other packages as well.