You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.0 KiB
Go

3 years ago
package iter
import (
"constraints"
)
type span[T constraints.Integer] struct {
3 years ago
start T
end T
step T
}
type spanIter[T constraints.Integer] struct {
start T
end T
3 years ago
step T
3 years ago
next T
3 years ago
}
3 years ago
func (s span[T]) Iter() Ator[T] {
return &spanIter[T]{
start: s.start,
end: s.end,
step: s.step,
next: s.start,
}
}
func (s *spanIter[T]) Next(n *T) bool {
if s.next >= s.end {
3 years ago
return false
}
*n = s.next
s.next += s.step
return true
}
3 years ago
func (s spanIter[T]) Iter() Ator[T] { return &s }
// Span creates a span of integers between start and end. The is analagous to
// the "range" function in Python, but since range already means something in
// Go, span is the chosen name to avoid confusion with Go's concept of range.
func Span[T constraints.Integer](start, end T) Able[T] {
return &span[T]{
start: start,
end: end,
step: 1,
}
3 years ago
}
// Step is the same as span, but allows for step sizes greater than 1
3 years ago
func Step[T constraints.Integer](start, end, step T) Able[T] {
return &span[T]{
start: start,
end: end,
step: step,
}
3 years ago
}