First class environments: Difference between revisions

→‎{{header|Kotlin}}: Replaced existing code with 'purer' though more long-winded version.
(Added Kotlin)
(→‎{{header|Kotlin}}: Replaced existing code with 'purer' though more long-winded version.)
Line 742:
 
=={{header|Kotlin}}==
This is based on the C entry except that, instead of using object references (Kotlin/JVM doesn't support explicit pointers) to switch between environments, it saves and restores the actual values of the two variables on each job switch. I see no reason why objects shouldn't be used to represent the environments as long as they have no member functions.
{{trans|C}}
<lang scala>// version 1.1.3
 
Line 749:
const val JOBS = 12
val envs = List(JOBS) { Environment(it + 1, 0) }
var envseq = envs[0] // stores reference to// 'currentseq' for current environment
var count = 0 // 'count' for current environment
var currId = 0 // index of current environment
 
fun switchTo(id: Int) {
if (id != currId) {
envs[currId].seq = seq
envs[currId].count = count
currId = id
}
envseq = envs[id] .seq
count = envs[id].count
}
 
fun hailstone() {
print("%4d".format(env.seq))
if (env.seq == 1) return
env.count++
env.seq = if (env.seq % 2 == 1) 3 * env.seq + 1 else env.seq / 2
}
 
funval switchToallDone get(id): Int)Boolean {
for (a in 0 until JOBS) {
env = envs[id]
switchTo(a)
if (seq != 1) return false
}
return true
}
 
Line 770 ⟶ 786:
println()
}
while (envs.any { it.seq != 1 } allDone)
 
println("\nCOUNTS:")
for (a in 0 until JOBS) {
switchTo(a)
print("%4d".format(env.count))
}
println()
9,482

edits