Variable declaration reset: Difference between revisions

J
(J)
Line 170:
5
</pre>
 
=={{header|J}}==
 
It may be difficult to say what is natural here, from the J perspective.
 
First off, the idiomatic J approach to finding indices of numbers which match their predecessors would be:
 
<lang J> 1+I.(}:=}.) 1,2,2,3,4,4,5
2 5</lang>
 
In other words, compare adjacent numbers (which results in a list of results one element shorter than the argument), find the indices of the matches (which would be the indices of the pairs which match) and add one (to get the indices in the original list of the second value of each of the pairs).
 
Also, J's <tt>for</tt> loop is analogous to javascript's foreach loop (and also tracks and makes available the index of the current value, which is useful when working with parallel lists). So we have to use J's while loop to approximate the javascript implementation.
 
But, also, J makes no distinction between a variable declaration and a variable assignment. And this task seems to be asking about how we handle that distinction.
 
Anyways, here's a rough approximation of what the task is asking for:
 
<lang J>same2=: {{
i=. 0
r=. ,EMPTY
while. i < #y do.
curr=. i{y
if. i>0 do.
if. curr=prev do.
r=. r,i
end.
end.
prev=. curr
i=. i+1
end.
r
}}</lang>
 
This gives us:
 
<lang J> same2 1,2,2,3,4,4,5
2 5</lang>
 
But, since we were unable to declare 'prev' before it was assigned, we have no way of moving that declaration of 'prev' outside of the loop. We could add a declaration of 'prev' outside of the loop,
 
<lang J>same3=: {{
i=. 0
r=. ,EMPTY
prev=. 99
while. i < #y do.
curr=. i{y
if. i>0 do.
if. curr=prev do.
r=. r,i
end.
end.
prev=. curr
i=. i+1
end.
r
}}</prev>
 
But it would not alter the generated result.
 
In other words, J's control words (like '<tt>while.</tt>') do not create new variable scopes.
 
=={{header|Java}}==
6,951

edits