Jump to content

First class environments: Difference between revisions

Added Wren
m (→‎{{header|REXX}}: reduced the font size to 75% for the first output section.)
(Added Wren)
Line 2,067:
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|Wren}}==
{{libheader|Wren-fmt}}
In Wren classes satisfy the definition of first-class objects in that: "they can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable."
 
It also appears that they can represent first-class environments in that they can encapsulate a set of variables (the class's fields) and code (the class's methods) which acts on those variables.
 
So that's what we use here. However, to create a dynamic class you have to wrap it in a function which then returns a reference to the class object.
<lang ecmascript>import "/fmt" for Fmt
 
var environment = Fn.new {
class E {
construct new(value, count) {
_value = value
_count = count
}
 
value { _value }
count { _count }
 
hailstone() {
Fmt.write("$4d", _value)
if (_value == 1) return
_count = _count + 1
_value = (_value%2 == 0) ? _value/2 : 3*_value + 1
}
}
return E
}
 
// create and initialize the environments
var jobs = 12
var envs = List.filled(jobs, null)
for (i in 0...jobs) envs[i] = environment.call().new(i+1, 0)
System.print("Sequences:")
var done = false
while (!done) {
for (env in envs) env.hailstone()
System.print()
done = true
for (env in envs) {
if (env.value != 1) {
done = false
break
}
}
}
System.print("Counts:")
for (env in envs) Fmt.write("$4d", env.count)
System.print()</lang>
 
{{out}}
<pre>
Sequences:
1 2 3 4 5 6 7 8 9 10 11 12
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
Counts:
0 1 7 2 5 8 16 3 19 6 14 9
</pre>
9,485

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.