BlueStyle
BlueStyle copied to clipboard
Guidelines for nested functions
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
Closures necessarily must at least come after the variables they're capturing.
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
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.
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