[SOLVED] How to convert this line of code from Python to Julia?

Issue

In brief, I have the code below in Python

[n, m] = f()

and I want to convert it to Julia, which will not be more than one line (I hope).

Here is an example in Python:

from numpy import *

x = [0,1,2]
y = [3,4,5]
x = array(x)
y = array(y)

def f():
    z = concatenate((x, y))
    a = z*2
    b = z*3
    return [a, b]

def g():
    [n,m] = f()
    n = n/2
    m = m/3
    return [n, m]

print(g())

This is how I wanted it to be in Julia, but did not work:

x = [0,1,2]
y = [3,4,5]

function f()
    z = vcat(x, y)
    a = z*2
    b = z*3
    return [a, b]
end

function g()
    [n, m] = f()
    n = n/2
    m = m/3
    return [n, m]
end

print(g())

Here is how I made it work, but I do not want codes like this:

x = [0,1,2]
y = [3,4,5]

function f()
    z = vcat(x, y)
    a = z*2
    b = z*3
    global c = [a, b]
    return c
end

function g()
    n = c[1]
    m = c[2]
    n = n/2
    m = m/3
    return [n, m]
end

f()
print(g())

Thank you very much.

Solution

Just drop square brackets like this:

x = [0,1,2]
y = [3,4,5]

function f()
    z = vcat(x, y)
    a = z*2
    b = z*3
    return a, b # here it is not needed, but typically in such cases it is dropped to return a tuple
end

function g()
    n, m = f() # here it is needed
    n = n/2
    m = m/3
    return n, m # here it is not needed, but typically in such cases it is dropped to return a tuple
end

print(g())

The reason why it is typically better to return a Tuple rather than a vector is that Tuple does not perform auto promotion of values (+ it is non-allocating):

julia> (1, 2.0) # here 1 stays an integer
(1, 2.0)

julia> [1, 2.0] # here 1 got implicitly converted to 1.0
2-element Vector{Float64}:
 1.0
 2.0

Of course if you want such implicit behavior use a vector.

Answered By – Bogumił Kamiński

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.