Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassign function and avoid recursive definition in Julia

I need to operate on a sequence of functions

h_k(x) = (I + f_k( ) )^k g(x)

for each k=1,...,N.

A basic example (N=2, f_k=f) is the following:

f(x) = x^2
g(x) = x
h1(x) = g(x) + f(g(x))
h2(x) = g(x) + f(g(x)) + f(g(x) + f(g(x)))
println(h1(1)) # returns 2
println(h2(1)) # returns 6

I need to write this in a loop and it would be best to redefine g(x) at each iteration. Unfortunately, I do not know how to do this in Julia without conflicting with the syntax for a recursive definition of g(x). Indeed,

f(x) = x^2
g(x) = x
for i=1:2
    global g(x) = g(x) + f(g(x))
    println(g(1))
end

results in a StackOverflowError.

In Julia, what is the proper way to redefine g(x), using its previous definition?

P.S. For those who would suggest that this problem could be solved with recursion: I want to use a for loop because of how the functions f_k(x) (in the above, each f_k = f) are computed in the real problem that this derives from.

like image 413
bkxvx Avatar asked Dec 09 '25 11:12

bkxvx


1 Answers

I am not sure if it is best, but a natural approach is to use anonymous functions here like this:

let
    f(x) = x^2
    g = x -> x
    for i=1:2
        l = g
        g = x -> l(x) + f(l(x))
        println(g(1))
    end
end

or like this

f(x) = x^2
g = x -> x
for i=1:4
    l = g
    global g = x -> l(x) + f(l(x))
    println(g(1))
end

(I prefer the former option using let as it avoids using global variables)

The issue is that l is a loop local variable that gets a fresh binding at each iteration, while g is external to the loop.

You might also check out this section of the Julia manual.

like image 116
Bogumił Kamiński Avatar answered Dec 12 '25 23:12

Bogumił Kamiński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!