First class environments: Difference between revisions

Added zkl
m (→‎{{header|REXX}}: added comments in the REXX section header. -- ~~~~)
(Added zkl)
Line 1,271:
1 1 1 1 1 1 1 1 1 1 1 1
Counts...
0 1 7 2 5 8 16 3 19 6 14 9
</pre>
 
 
=={{header|zkl}}==
In zkl, classes wrap state. All instances of a class share code but each instance binds code to itself. In this task, class creation, instead of returning a new class instance, it returns a bound function. Calling this function calculates the next hailstone in the environment the function is bound to. To get the counts from the class/environment, we ask the function for its container and then pull the count.
<lang zkl>class Env{
var n,cnt=0;
fcn init(_n){n=_n; returnClass(self.f)}
fcn f{
if(n!=1){
cnt += 1;
if(n.isEven) n=n/2; else n=n*3+1;
}
n
}
}</lang>
<lang zkl>var es=(1).pump(12,List,Env);
while(1){
ns:=es.run(True);
ns.pump(String,"%4d".fmt).println();
if (not ns.filter('!=(1))) break;
}
println("Counts:");
es.pump(String,fcn(e){"%4d".fmt(e.container.cnt)}).println();</lang>
{{out}}
<pre>
1 1 10 2 16 3 22 4 28 5 34 6
1 1 5 1 8 10 11 2 14 16 17 3
1 1 16 1 4 5 34 1 7 8 52 10
1 1 8 1 2 16 17 1 22 4 26 5
1 1 4 1 1 8 52 1 11 2 13 16
1 1 2 1 1 4 26 1 34 1 40 8
1 1 1 1 1 2 13 1 17 1 20 4
1 1 1 1 1 1 40 1 52 1 10 2
1 1 1 1 1 1 20 1 26 1 5 1
1 1 1 1 1 1 10 1 13 1 16 1
1 1 1 1 1 1 5 1 40 1 8 1
1 1 1 1 1 1 16 1 20 1 4 1
1 1 1 1 1 1 8 1 10 1 2 1
1 1 1 1 1 1 4 1 5 1 1 1
1 1 1 1 1 1 2 1 16 1 1 1
1 1 1 1 1 1 1 1 8 1 1 1
1 1 1 1 1 1 1 1 4 1 1 1
1 1 1 1 1 1 1 1 2 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
Counts:
0 1 7 2 5 8 16 3 19 6 14 9
</pre>
Anonymous user