Loops/Wrong ranges: Difference between revisions

Added Go
m (→‎{{header|Perl 6}}: remove redundant demo)
(Added Go)
Line 27:
|0||0||0||Start equal stop equal zero: zero increment
|}
 
=={{header|Go}}==
Go has only one loop, a 'for' statement, which supports four different syntactical forms commonly found in other C-family languages:
 
1. A C-like 'for' loop with initialization, condition and increment sections.
 
2. The 'while' loop functionality (condition only)
 
3. Infinite loop, equivalent to for(;;) (all sections omitted)
 
4. Looping over a range of values, similar to foreach etc. (using 'range' keyword).
 
It appears that either #1 or #4 fits the requirements of this task so I've written a function which generates the appropriate sequence using #1 (limited to a maximum of 10 elements as some sequences will be infinite). I've then applied #4 to the resulting sequence. All sequences include the stop value if it's actually reached.
<lang go>package main
 
import "fmt"
 
type S struct {
start, stop, incr int
comment string
}
 
var examples = []S{
{-2, 2, 1, "Normal"},
{-2, 2, 0, "Zero increment"},
{-2, 2, -1, "Increments away from stop value"},
{-2, 2, 10, "First increment is beyond stop value"},
{2, -2, 1, "Start more than stop: positive increment"},
{2, 2, 1, "Start equal stop: positive increment"},
{2, 2, -1, "Start equal stop: negative increment"},
{2, 2, 0, "Start equal stop: zero increment"},
{0, 0, 0, "Start equal stop equal zero: zero increment"},
}
 
func sequence(s S, limit int) []int {
var seq []int
for i, c := s.start, 0; i <= s.stop && c < limit; i, c = i+s.incr, c+1 {
seq = append(seq, i)
}
return seq
}
 
func main() {
const limit = 10
for _, ex := range examples {
fmt.Println(ex.comment)
fmt.Printf("Range(%d, %d, %d) -> ", ex.start, ex.stop, ex.incr)
fmt.Println(sequence(ex, limit))
fmt.Println()
}
}</lang>
 
{{out}}
<pre>
Normal
Range(-2, 2, 1) -> [-2 -1 0 1 2]
 
Zero increment
Range(-2, 2, 0) -> [-2 -2 -2 -2 -2 -2 -2 -2 -2 -2]
 
Increments away from stop value
Range(-2, 2, -1) -> [-2 -3 -4 -5 -6 -7 -8 -9 -10 -11]
 
First increment is beyond stop value
Range(-2, 2, 10) -> [-2]
 
Start more than stop: positive increment
Range(2, -2, 1) -> []
 
Start equal stop: positive increment
Range(2, 2, 1) -> [2]
 
Start equal stop: negative increment
Range(2, 2, -1) -> [2 1 0 -1 -2 -3 -4 -5 -6 -7]
 
Start equal stop: zero increment
Range(2, 2, 0) -> [2 2 2 2 2 2 2 2 2 2]
 
Start equal stop equal zero: zero increment
Range(0, 0, 0) -> [0 0 0 0 0 0 0 0 0 0]
</pre>
 
=={{header|Perl 6}}==
9,488

edits