Created
November 21, 2018 20:23
-
-
Save erriapo/c954fb6ac4cbd6f8768a63344f47ac9a to your computer and use it in GitHub Desktop.
Go lang implementation of python's range function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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