What languages are you using that don’t support that? Every language I use on a semi-monthly basis (Haskell, R, Python, Bash, Javascript, PHP, Elisp...) that I can think of supports defining a function inside a function (under various names like let/where local definitions, ‘inner functions’, what-have-you), and typically support even anonymous function definitions (lambdas).
I was thinking about Java and Python. The fact that you can just use lambdas first occurred to me at some point in between writing this and seeing your answer. I don’t know why it wasn’t obvious.
Aside from lambdas, Python has ‘inner functions’ where you just def inside a def. Java has anonymous inner classes and private functions, and Java 8 adds lambdas; I had to google this one, but apparently Java even has “local classes” which sounds like an exact match for what you want?
Lambdas in Java 8 can only access variables from the surrounding block as read-only. For example, if you want to calculate the sum of numbers between 1 and 100, this gives you a compile-time error:
int x = 0; IntStream.rangeClosed(1, 100).forEach(i → x += i);
If memory serves me well, in Pascal, local functions could also write to the variables they could see.
What languages are you using that don’t support that? Every language I use on a semi-monthly basis (Haskell, R, Python, Bash, Javascript, PHP, Elisp...) that I can think of supports defining a function inside a function (under various names like let/where local definitions, ‘inner functions’, what-have-you), and typically support even anonymous function definitions (lambdas).
I was thinking about Java and Python. The fact that you can just use lambdas first occurred to me at some point in between writing this and seeing your answer. I don’t know why it wasn’t obvious.
Aside from lambdas, Python has ‘inner functions’ where you just
def
inside adef
. Java has anonymous inner classes and private functions, and Java 8 adds lambdas; I had to google this one, but apparently Java even has “local classes” which sounds like an exact match for what you want?Lambdas in Java 8 can only access variables from the surrounding block as read-only. For example, if you want to calculate the sum of numbers between 1 and 100, this gives you a compile-time error:
If memory serves me well, in Pascal, local functions could also write to the variables they could see.