When function shouldn't return anything

Below is the code which I am working on. I have a Composite type called NearestNeighbor which has arrays to be passed on to processing.

type NearestNeighbor
  Xrows::Array{Float64,2}
  Yrows::Vector{Float64}

  function NearestNeighbor()
    new(Array{Float64,2}(0,0), Vector{Float64}(0))
  end
end

nn=NearestNeighbor()

function trainModel{Float64}(nn::NearestNeighbor,Xvals::SharedArray{Float64,2},Yvals::Vector{Float64})
  nn.Xrows=Xvals
  nn.Yrows=Yvals
end

The above trainModel just assigns training data, it does not have to return anything. And I have predictModel function which uses nn.Xrows and nn.Yrows for further processing.
Should I return nothing or return or none in the trainModel function or
Kindly let me know what is right way to go about this issue

Thank You.

  1. I am not sure if you need such a function, when you can define a constructor (see example below) which initializes your data.
    Does this achieve what you want to do?
  2. I have no experience with SharedArrays, but Xval seems to be a different type than nn.Xrows. I do not know whether your function will work given the type of Xrows.
  3. if it ‘does not have to return anyhting’ you can put ‘return nothing’ on the last line (see below)
  4. It is customary to use ! (at the end of the function name) for Julia functions that modify arguments (like push!([1,2,3],99) (in case you want to keep your trainModel function I would rename it to trainModel!)

hope that helps

type NearestNeighbor
  Xrows::Array{Float64,2}
  Yrows::Vector{Float64}

  function NearestNeighbor()
    new(Array{Float64,2}(0,0), Vector{Float64}(0))
  end
  function NearestNeighbor(a,b)
    new(a,b)
  end
end

x=rand(2,9)
y=rand(9)

my_nn=NearestNeighbor(x,y) #no need to call trainModel function


function trainModel!{Float64}(nn::NearestNeighbor,Xvals::SharedArray{Float64,2},Yvals::Vector{Float64})
  nn.Xrows=Xvals
  nn.Yrows=Yvals
  return nothing
end


2 Likes

I am guessing you are asking this because languages like C/C++ with a void return type do not return a value when the return statement is omitted.

Julia seems to inherit from the Lisp programming languages when it comes to return values:
→ It returns whatever value that results from the last statement in your function (in your case, that means it returns Yvals).

I personally find it cleaner to return nothing in this case - but I do tend to forget to do so coming from a C/C++ background. I find that not returning nothing causes potential confusion for the function’s user.

There are 3 (equally valid) ways I might use to do this. All 3 return nothing:

Method 1

function myfunc()
    #do something
    return
end

Method 2

function myfunc()
    #do something
    return nothing
end

Method 3

function myfunc()
    #do something
    nothing
end
3 Likes

@bernhard Thank you very much for suggesting to use constructor itself as that approach seems better and in pointing out the convention of using ! cheers.