Home > Enterprise >  Recursive function in Julia
Recursive function in Julia

Time:05-24

Is there a way in Julia to smoothly define a recursive function?

function f(x_0, y_0)

    x_1 = g1(x_0,y_0)
    y_1 = g2(x_0,y_0)

    x_2 = g1(x_1,y_1)
    y_2 = g2(x_1,y_1)

    x_3 = g1(x_2,y_2)
    y_3 = g2(x_2,y_2)
    
    x_4 = g1(x_3,y_3)
    y_4 = g2(x_3,y_3)
    
    return x_2,y_2
end

In particular, I want to be able to call the function and give parameter that would specify the circle of the recursion. Something like this:

f(x_0, y_0, circle = 2)
>> x_2, y_2
f(x_0, y_0, circle = 3)
>> x_3, y_3

CodePudding user response:

If you define

function apply_n(f, x_0, cycle_len)
    for _ in 1:cycle_len
        x_0 = f(x_0)
    end
    return x0
end

and call apply_n((x,y)->(g1(x,y),g2(x,y)), (x_0,y_0), 3) it will work.

  • Related