BlueStyle icon indicating copy to clipboard operation
BlueStyle copied to clipboard

Guidelines for nested functions

Open mattBrzezinski opened this issue 5 years ago • 4 comments
trafficstars

Just wanted to open up a chat about if functions should be nested, and if so where should they live?

function _bar(v::String)
  return string(v, v)
end

function foo()
  var = "Test"

  return _bar(var)
end

OR

function foo()
  function _bar(v::String)
    return string(v, v)
  end

  var = "Test"
  return _bar(var)
end

OR

function foo()
  var = "Test"

  function _bar(v::String)
    return string(v, v)
  end

  return _bar(var)
end

mattBrzezinski avatar Aug 26 '20 21:08 mattBrzezinski

Closures necessarily must at least come after the variables they're capturing.

iamed2 avatar Aug 27 '20 14:08 iamed2

Function should not be nested, unless they are closures

e.g.

# Yes
function _bar(v::String)
  return string(v, v)
end

function foo()
  var = "Test"
  return _bar(var)
end

# No 
function foo()
  function _bar(v::String)
    return string(v, v)
  end
  var = "Test"
  return _bar(var)
end
# Yes 
function func(x)
  y = g(x)
  function _bar(v::String)
    return string(v, y)
  end
  return y, _bar
end

# Not valid: 
function _bar(v::String)
  return string(v, y)
end

function func(x)
  y = g(x)
  return y, _bar
end

nickrobinson251 avatar Sep 06 '20 16:09 nickrobinson251

ChainRules.jl nests functions that are not closures sometimes.

Here is one https://github.com/JuliaDiff/ChainRules.jl/blob/ead0c4bb0353e1da510d46e28bb26dddbd5d1157/src/rulesets/Base/fastmath_able.jl#L74-L76

Is this a case of exceptions are exceptional?

Or a sign of a wider pattern, where if you are returning the function, then it is also permitted for that function to be a nested function.

oxinabox avatar Sep 07 '20 16:09 oxinabox

Is this a case of exceptions are exceptional?

Maybe; that was my first thought.

if you are returning the function, then it is also permitted for that function to be a nested function

i could very easily be convinced of this

nickrobinson251 avatar Sep 07 '20 17:09 nickrobinson251