What is the best way to loop a function over a list continuously in Julia?

Hi this is a beginner programming question but I am trying to run a function on a list of variables repeatedly until I request that it stop. i.e.

list = [A,B,C]  

function(A)
function(B)
function(C)
function(A)
function(B)...

I was wondering if there was a better way to do it than the clunky solution I came up with.

list = [ A, B, C] 
function runfunc(list)
    cont = Ref(true)
    k = 1  
    @async while cont[] 
        function(list[k])
        if k <3
           k+= 1
        elif k == 3 
           k =0
        end
    end
    return(cont) 
end    

is this the correct way to approach this in Julia? is there a better way to start the loop over again without having to go through a test for conditions? Any corrections/ insights would be appreciated thanks!

for the specifics of the counter, you can do:

k = 0
while cont[]
    k += 1
    f(list[k%3 + 1])
end

to run that continously you can do something like:

julia> const stop = Ref(false);

julia> function run()
           global stop
           k = 0
           @async while !stop[]
               k += 1 
               print('.')
               sleep(5)
           end
       end
run (generic function with 1 method)

(not sure if Iā€™m helping)

1 Like
help?> Iterators.cycle
  cycle(iter)

  An iterator that cycles through iter forever. If iter is empty, so is cycle(iter).
list = [ A, B, C] 
function runfunc(list)
  cont = Ref(true)

  @async for listitem in Iterators.cycle(list)
    cont[] || break
    myfunction(listitem)
  end
  return(cont) 
end
6 Likes

A more bug-resistant option is

f(list[mod1(k, 3)])
1 Like

Wow! thanks to everyone for the amazing suggestions. Modulo works great. What exactly is Julia doing in the line cont[] || break in @digital_carverā€™s code? Is there somewhere I can find out more about that? Is that a shorthand form of an if, elif statement?

if cond[] break end

You can search for the meaning of the operator typing ? || in the repl

1 Like

https://docs.julialang.org/en/v1/manual/control-flow/#Short-Circuit-Evaluation

1 Like