Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guidelines for nested functions #58

Open
mattBrzezinski opened this issue Aug 26, 2020 · 4 comments
Open

Guidelines for nested functions #58

mattBrzezinski opened this issue Aug 26, 2020 · 4 comments

Comments

@mattBrzezinski
Copy link
Member

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
@iamed2
Copy link
Collaborator

iamed2 commented Aug 27, 2020

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

@nickrobinson251
Copy link
Contributor

nickrobinson251 commented Sep 6, 2020

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

@oxinabox
Copy link
Member

oxinabox commented Sep 7, 2020

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.

@nickrobinson251
Copy link
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants