Variable declaration reset

Revision as of 23:11, 15 April 2022 by Tigerofdarkness (talk | contribs) (Added Algol 68)

A decidely non-challenging task to highlight a potential difference between programming languages.

Variable declaration reset is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
If your programming language does not support block scope (eg assembly) it should be omitted from this task.

ALGOL 68

Algol 68n should produce no output as each iteration of the loop has a separate instance of the variables.
The Algol 68 euivalent of the Phix program is as below, whether this works as expected depends on how the implementation treats uninitialised variables... <lang algol68>BEGIN

   []INT s = ( 1, 2, 2, 3, 4, 4, 5 );
   FOR i TO ( UPB s -LWB s ) + 1 DO
       INT curr := s[ i ], prev;
       IF i > 1 AND curr = prev THEN
           print( ( i, newline ) )
       FI;
       prev := curr
   OD

END</lang>

Output:

with Algol 68G

5             IF i > 1 AND curr = prev THEN
                                  1
a68g-2.8.3: runtime error: 1: attempt to use an uninitialised INT value (detected in VOID conditional-clause starting at "IF" in this line).

with Rutgers Algol 68:
No output.

JavaScript

<lang javascript><!DOCTYPE html> <html lang="en" >

<head>
 <meta charset="utf-8"/>
 <meta name="viewport" content="width=device-width, initial-scale=1"/>
 <title>variable declaration reset</title>
</head>
<body>
 <script>

"use strict"; let s = [1, 2, 2, 3, 4, 4, 5]; for (let i=0; i<7; i+=1) {

   let curr = s[i], prev;
   if (i>1 && (curr===prev)) {
       console.log(i);
   }
   prev = curr;

}

 </script>
</body>

</html></lang> No output
Manually moving the declaration of prev to before the loop, or changing the third "let" to "var" (causes legacy hoisting and) gives:

Output:
2
5

Phix

with javascript_semantics
sequence s = {1,2,2,3,4,4,5}
for i=1 to length(s) do
    integer curr = s[i], prev
    if i>1 and curr=prev then
        ?i
    end if
    prev = curr
end for
Output:
3
6

Like the first/unchanged JavaScript example, under pwa/p2js there is no output (at least as things currently stand)
Obviously you can achieve consistent results by manually hoisting the declaration of prev to before/outside the loop.