Skip to content

Instantly share code, notes, and snippets.

@erriapo
Created November 21, 2018 20:23
Show Gist options
  • Save erriapo/c954fb6ac4cbd6f8768a63344f47ac9a to your computer and use it in GitHub Desktop.
Save erriapo/c954fb6ac4cbd6f8768a63344f47ac9a to your computer and use it in GitHub Desktop.
Go lang implementation of python's range function
// https://docs.python.org/3/library/functions.html#func-range
package main
import (
"fmt"
)
type Range struct {
Step int32
Max int32
Start int32
}
type void struct{}
func NewRangeMore(start, max, step int32) Range {
return Range{Step: step, Max: max, Start: start}
}
func NewRange(max int32) Range {
return NewRangeMore(1, max, 1)
}
func (r Range) For(looper func(i int32)) {
if r.Step == 0 {
panic("Step cannot be zero")
}
if r.Start > 0 && r.Max < 0 && r.Step < 0 && r.Start > r.Max {
for i := r.Start; i > r.Max; i = i + r.Step {
looper(i)
}
} else if r.Step > 0 && r.Max > 0 && r.Start > 0 && r.Start <= r.Max {
for i := r.Start; i < r.Max; i = i + r.Step {
looper(i)
}
} else {
panic("bad")
}
}
func main() {
r := NewRangeMore(5, -1, -1)
fmt.Printf("%#v\n", r)
r.For(func(i int32) {
fmt.Printf("\tlooping at i %d\n", i)
})
s := NewRange(3)
fmt.Printf("%#v\n", s)
s.For(func(i int32) {
fmt.Printf("\tlooping at i %d\n", i)
})
h := NewRange(-1)
fmt.Printf("%#v\n", h)
h.For(func(i int32) {
fmt.Printf("\tlooping at i %d\n", i)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment