Is it possible to make this function work in Julia?

Sorry this takes so much verbiage. I know that most of the functions I need to write will have several variables already defined prior to the definition of the function. The value of these variables must be accessible within the body of the function and must be able to be modified within the body of the function. The revised values must be returned by the function after which the returned values can be used to update the original values of those variables.

The concept that I thought was feasible was to pass the initial values of the variables as arguments of the function. And the revised values, created when the function is called, would be returned by the function as a tuple of whatever size is required. The values of the components of the returned tuple could then be used to update the original values of the variables.

So far I haven’t been able to get this to work. I don’t know whether this is because this simply isn’t possible in Julia or because I’m just missing a couple crucial ingredients. Here’s the example that I haven’t gotten to work:

ftest1.jl a test program to see if a function can overcome scope problems.

arr = [“abc”,“def”,“ghi”,“jkl”,“mno”]
x = 15
y = 25
println(“Prior to function definition: arr=”,arr," x=“,x,” y=“,y)
function Example(arri,xi,yi)
xi = xi + yi
yi = xi * yi
arrt = arri
arri[1] = arrt[5], arri[2]=arrt[4], arri[4] =arrt[2], arri[5]=arrt[1]
println(“Within function definition: arri=”,arri,” xi=“,xi,” yi=“,yi)
return arri,xi,yi
end
(arr,x,y) = Example(arr,x,y)
println(“After completion of function call: arr=”,arr,” x=“,x,” y=",y)

Please use ``` around code to make it format properly. It makes it much easier to read.

1 Like

All that is needed to make your code work is to replace

with

arri[1] = arrt[5]; arri[2]=arrt[4]; arri[4] =arrt[2]; arri[5]=arrt[1]

(i.e. ; instead of ,)

2 Likes

Your function mutates the input array. It does not need to be returned.

arr = ["abc","def","ghi","jkl","mno"]
x = 15
y = 25
println("Prior to function definition: arr=",arr," x=",x," y=",y)

function Example!(arri,xi,yi)
    xi = xi + yi
    yi = xi * yi
    arrt = arri
    arri[1] = arrt[5]; arri[2]=arrt[4]; arri[4] = arrt[2]; arri[5]=arrt[1];
    println("Within function definition: arri=",arri," xi=",xi," yi=",yi)
    return xi,yi
end

x, y = Example!(arr,x,y)
println("After completion of function call: arr=",arr," x=",x," y=",y)
julia> include("test1.jl")
Prior to function definition: arr=["abc", "def", "ghi", "jkl", "mno"] x=15 y=25
Within function definition: arri=["mno", "jkl", "ghi", "jkl", "mno"] xi=40 yi=1000
After completion of function call: arr=["mno", "jkl", "ghi", "jkl", "mno"] x=40 y=1000