Home > OS >  how to call a function to another function in julia?
how to call a function to another function in julia?

Time:10-18

I am writing a code in julia but I am unable to call a function from another function. Code is:

function add(x, y)
    if x == 3 && y ==1
        z =0
    else x == 0 && y ==0
        z =1
    end
    return z
end

function width(a, b, c)
    add(x,y)
    .....
end

The variables in add function will be used in width function but as I am new to julia, I am unable to call add in the other function. Kindly guide. Edit: I tried declaring with the z but it also didn't worked

struct z 
    a::Int 
    b::Int 
end

CodePudding user response:

There are two problems in your code that are not related to Julia per se. First problem in the add function: if x == 3 && y == 1 the output should be z = 0, else if x == 0 && y == 0, actually the if was missing, the output should be z = 1. Now what will be the output if, e.g., x = 1 && y == 1? The answer is nothing and z will be undefined.

To fix the add function, you should add a default branch for the if-else.

function add(x, y)
    if x == 3 && y == 1
        z = 0
    elseif x == 0 && y == 0
        z = 1
    else 
        z = -1 # some default
    end
    return z
end

The same function could be written more concisely as:

function add(x, y)
    x == 3 && y == 1 && return 0
    x == 0 && y == 0 && return 1
    return -1 # some default
end

which can even be written in a one-liner like this:

add(x, y) = x == 3 && y == 1 ? 0 : x == 0 && y == 0 ? 1 : -1 # some default

The second problem is with the width function. x and y are not defined inside the body of the width function. So, you can't call add(x, y). It should be z = add(a, b) where z should be used in subsequent calculations. Finally, check what the third argument c is for, otherwise, remove it.

function width(a, b, c)
    z = add(a, b)
    .....
end
  • Related