Variable declaration reset: Difference between revisions

Added Go
(Added Wren)
(Added Go)
Line 79:
 
{ 1 2 2 3 4 4 5 } 2 <clumps> [ all-eq? ] arg-where 1 v+n .</lang>
 
=={{header|Go}}==
Note firstly that unassigned variables are impossible in Go. If a variable is created (using the 'var' keyword) without giving it an explicit value, then it is assigned the default value for its type which in the case of numbers is zero. Fortunately, this doesn't clash with values in the slice in the following program.
<lang go>package main
 
import "fmt"
 
func main() {
s := []int{1, 2, 2, 3, 4, 4, 5}
 
// There is no output as 'prev' is created anew each time
// around the loop and set implicitly to zero.
for i := 0; i < len(s); i++ {
curr := s[i]
var prev int
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
 
// Now 'prev' is created only once and reassigned
// each time around the loop producing the desired output.
var prev int
for i := 0; i < len(s); i++ {
curr := s[i]
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
}</lang>
 
{{out}}
<pre>
2
5
</pre>
 
=={{header|JavaScript}}==
9,485

edits