Stair-climbing puzzle: Difference between revisions

Ada solution added
(→‎{{header|Tcl}}: ++ smalltalk)
(Ada solution added)
Line 4:
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure. Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
 
=={{header|Ada}}==
<lang Ada>
procedure Step_Up is
begin
while not Step loop
Step_Up;
end loop;
end Step_Up;
</lang>
The following is a test program simulating Step:
<lang Ada>
with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
 
procedure Scaffolding is
package Try is new Ada.Numerics.Discrete_Random (Boolean);
use Try;
Dice : Generator;
Level : Integer := 0;
 
function Step return Boolean is
begin
if Random (Dice) then
Level := Level + 1;
Ada.Text_IO.Put_Line ("Climbed up to" & Integer'Image (Level));
return True;
else
Level := Level - 1;
Ada.Text_IO.Put_Line ("Fell down to" & Integer'Image (Level));
return False;
end if;
end Step;
procedure Step_Up is
begin
while not Step loop
Step_Up;
end loop;
end Step_Up;
begin
Reset (Dice);
Step_Up;
end Scaffolding;
</lang>
Sample output:
<pre>
Fell down to-1
Climbed up to 0
Fell down to-1
Climbed up to 0
Fell down to-1
Fell down to-2
Climbed up to-1
Climbed up to 0
Climbed up to 1
</pre>
=={{header|C}}==
The same solution of the [[Stair Climbing#C%2B%2B|C++]] code can be used; the initial declaration of a variable inside a for loop is C99.