Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Java also had this problem with anonymous classes. The solution is usually to introduce a functor. Being pass-by-value, it captures the state of the variables at its call time, which helps remove some ambiguity in your code.

If you try to do something weird with variable capture, then any collections you accumulate data into (eg, for turning an array into a map), will behave differently than any declared variables.

Go is trying to thread the needle by only having loop counters work this way. But that still means that some variables act weird (it's just a variable that tends to act weird anyway). And I wonder what happens when you define multiple loop variables, which people often do when there will be custom scanning of the inputs.



Java has never had this problem with variables (either in a for loop or free-floating ones), since Java has never had support for closures.

There is one somewhat similar problem in Java that you're maybe thinking of: anonymous classes that reference fields of the current object. I don't think that behavior is surprising, and there are very important use cases for it.

What Go is doing is perfectly sensible. The ability to capture variables is extremely powerful, and often desired. It's just the unexpected scoping of loop variables that introduces a problem. The following code is doing exactly what most people would expect, for example:

  a := 0
  incr := func() {a += 1}
  print := func() {fmt.Printf("%d", a)}
  print() // prints 0
  incr()
  print() //prints 1


> An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

So no, Java didn’t have this problem.


Which of the various meanings of the word 'functor' are you using here?


Function that returns a function.

You pass your counter into the function, it returns a function that remembers the original value, not the value as it keeps iterating later on in the caller.


That's just a higher order function?

That's an interesting definition. I thought you would either go with https://en.wikipedia.org/wiki/Functor_(functional_programmin... or with https://en.wikipedia.org/wiki/Function_object

https://en.wikipedia.org/wiki/Functor_(disambiguation) has a few more choices, but doesn't seem to have yours.


Functor must be one of the worst overloaded terms in all of computing.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: