Reputation: 7679
I would like to get the following values 1, 10, 20, 30, ...
but I do not how to do it Julia:
for (count, x) in enumerate(["x1", "x1.y1", "x1.y1.xyz22", "x133001", "x133001.y1", "x133001.y1.xyz22"])
println(count + 10 - 1)
end
What would the best way?
Thank you in advance,
Update
The below code failed to run:
julia> count = 1
1
julia> for x in ["x1", "x1.y1", "x1.y1.xyz22", "x133001", "x133001.y1", "x133001.y1.xyz22"]
if count == 1
count = 10
else
count += 10
println(count)
end
ERROR: syntax: incomplete: "for" at REPL[6]:1 requires end
Stacktrace:
[1] top-level scope at REPL[5]:0
Upvotes: 0
Views: 822
Reputation: 10010
For inifinite streams one could use Python-like generators which are available in ResumableFunctions.jl
package.
Install by:
using Pkg
Pkg.add("ResumableFunctions")
using ResumableFunctions
Generate an inifnite stream generator function:
@resumable function infstream(start = 0, first_val = 0, step=1)
"It starts with start value steps by step. However, for first value
first_val is returned."
c = start
while 1==1
@yield if (c==start) first_val else c end
c = c + step
end
end
You initialize an instance by:
mycount = infstream(0, 1, 10)
mycount() # 1
mycount() # 10
mycount() # 20
# ... etc ad infinitum
For your problem you can use it like this:
counter, result = infstream(0, 1, 10), []
for x in ["x1", "x1.y1", "x1.y1.xyz22", "x133001", "x133001.y1", "x133001.y1.xyz22"]
push!(result, counter())
end
which gives:
julia> result
6-element Array{Any,1}:
1
10
20
30
40
50
With the resumable infstream()
function, you can create any thinkable counters for arithmetic inifinite series.
Upvotes: 1
Reputation: 6086
Here is one of an indefinite number of exact solutions. With (count, x) you can mostly use count but use x for the start and end cases:
for (count, x) in enumerate(
["x1", "x1.y1", "x1.y1.xyz22", "x133001", "x133001.y1", "x133001.y1.xyz22"]
)
if x == "x1"
print(count, ", ")
else
print(10 * (count - 1), ", ")
end
if x == "x133001.y1.xyz22"
println("...")
end
end
Gets you: 1, 10, 20, 30, 40, 50, ...
Upvotes: 3