Jump to content

Stair-climbing puzzle: Difference between revisions

→‎E: add E example
(added ocaml)
(→‎E: add E example)
Line 50:
true))
</lang>
 
=={{header|E}}==
 
This is at first a very direct {{trans|Clojure}}
 
The problem framework:
 
<lang e>var level := 41
var prob := 0.5001
 
def step() {
def success := entropy.nextDouble() < prob
level += success.pick(1, -1)
return success
}</lang>
 
Counting solution:
 
<lang e>def stepUpCounting() {
var deficit := 1
while (deficit > 0) {
deficit += step().pick(-1, 1)
}
}</lang>
 
Ordinary recursive solution:
<lang e>def stepUpRecur() {
if (!step()) {
stepUpRecur()
stepUpRecur()
}
}</lang>
 
Eventual-recursive solution. This executes on the vat ''queue'' rather than the stack, so while it has the same space usage properties as the stack-recursive version it does not use the stack which is often significantly smaller than the heap. Its return value resolves when it has completed its task.
 
<lang e>def stepUpEventualRecur() {
if (!step()) {
return when (stepUpEventualRecur <- (),
stepUpEventualRecur <- ()) -> {}
}
}</lang>
 
Fully eventual counting solution. This would be appropriate for controlling an actual robot, where the climb operation is non-instantaneous (and therefore eventual):
 
[[Category:E examples needing attention]]
<lang e>def stepUpEventual() {
# This general structure (tail-recursive def{if{when}}) is rather common
# and probably ought to be defined in a library.
def loop(deficit) {
if (deficit > 0) {
return when (def success := step()) -> {
loop(deficit + success.pick(-1, 1))
}
}
}
return loop(1)
}</lang>
 
=={{header|OCaml}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.