octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Nested functions, documented?


From: John W. Eaton
Subject: Re: Nested functions, documented?
Date: Mon, 21 Nov 2011 16:25:28 -0500

On 19-Nov-2011, David Shih wrote:

| I ran into the same problem where my Matlab code using nested function is
| affected by the variable scope issue.
| 
| I have not seen a workaround on the list, so I am providing one here:
| 
| You can use anonymous functions with subfunctions to achieve the same effect
| as nested functions.
| It may even be desired that the programmer explicitly pass the variables
| into a subfunction using an anonymous function, so that nested function
| variable scopes do not become a mess.
| 
| 
| An example:
| 
| *Nested version*:
| 
| function y = primary_function(x, a, b)
| 
|   function z = nested_function(x)
|     % nested_function accesses variables a and b from the parent function
|     z = x + a + b;
|   end
| 
|   y = nested_function(x);
| 
| end

| function y = primary_function(x, a, b)
|   y = sub_function( @(x) sub_function(x, a, b) );
| end
| 
| function z = sub_function(x, a, b)
|   % sub_function accesses parameter variables a and b, which are in scope
|   z = x + a + b;
| end

Given that you are writing this complex expression:

   y = sub_function( @(x) sub_function(x, a, b) );

which already involves A and B as arguments to the subfunction, why
not simplify things and write

   y = subfunction (x, a, b);

instead?

Also, the version with the function handle trick is not equivalent to
nested functions because nested functions can change values in the
calling scope.  For example, with Matlab, I think the following
program will print x = 3 and a = 4 and y will be undefined outside the
scope foo the nested function:

  function foo ()
    x = 1;
    a = 2;
    function bar (y)
      y = -1;
      x = 3;
      a = 4;
    end
    bar (x);
    x
    a
    y
  end

I don't think you can get those semantics from some trick with
function handles and subfunctions because the function handle gets a
copy of the variables from the calling scope, and the subfunction
can't directly modify values in the caller.

And, I would add, those semantics are precisely what makes nested
functions such an awful software maintenance nightmare.  At the very
least, a way to declare variables as local to a nested function should
have been added to the language at the same time.

jwe


reply via email to

[Prev in Thread] Current Thread [Next in Thread]