I am a Nice beginner, so I don't know if this has been discussed before, but I found some unexpected behavior involving the extended for loop and threads last night. Here's an example:
package loopBug;
void main(String[] args){
for(String current : ["one","two","three"])
new SomeThread( action: ()=>{ println(current); } ).start();
}
The anonymous method sent to SomeThread runs in the same scope as the for loop, with the result that it changes with every iteration; after the loop finishes, all the threads are running the action of the last iteration.
Does that seem odd to anyone else?
It is fairly easy to fix, by making another function that builds a void->void function:
Yes, that is to be expected from a Nice closure.
In Java you can pass only read-only (final) variables to the closure, but in Nice you can access and modify any context variables from a closure.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
In some functional languages this is deliberately used as a primary way to communicate between threads. One example, if i'm not mistaken, is the Felix Language. http://felix.sourceforge.net/
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
I am a Nice beginner, so I don't know if this has been discussed before, but I found some unexpected behavior involving the extended for loop and threads last night. Here's an example:
package loopBug;
void main(String[] args){
for(String current : ["one","two","three"])
new SomeThread( action: ()=>{ println(current); } ).start();
}
class SomeThread extends Thread{
void->void action;
run(){
for(int n=0;n!=5;n++)
{
action();
Thread.sleep(100);
}
}
}
The anonymous method sent to SomeThread runs in the same scope as the for loop, with the result that it changes with every iteration; after the loop finishes, all the threads are running the action of the last iteration.
Does that seem odd to anyone else?
It is fairly easy to fix, by making another function that builds a void->void function:
<T> void->void bind(T->void func,T param)=()=>{func(param);};
Yes, that is to be expected from a Nice closure.
In Java you can pass only read-only (final) variables to the closure, but in Nice you can access and modify any context variables from a closure.
In some functional languages this is deliberately used as a primary way to communicate between threads. One example, if i'm not mistaken, is the Felix Language. http://felix.sourceforge.net/