iter

package module
v0.0.0-...-0252883 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 15, 2019 License: BSD-3-Clause Imports: 8 Imported by: 0

README

iter

Go implementation of C++ STL iterators and algorithms.

Less hand-written loops, more expressive code.

README translations: 简体中文

GoDoc Build Status codecov Go Report Card

Motivation

Although Go doesn't have generics, we deserve to have reuseable general algorithms. iter helps improving Go code in several ways:

  • Some simple loops are unlikely to be wrong or inefficient, but calling algorithm instead will make the code more concise and easier to comprehend. Such as AllOf, FindIf, Accumulate.

  • Some algorithms are not complicated, but it is not easy to write them correctly. Reusing code makes them easier to reason for correctness. Such as Shuffle, Sample, Partition.

  • STL also includes some complicated algorithms that may take hours to make it correct. Implementing it manually is impractical. Such as NthElement, StablePartition, NextPermutation.

  • The implementation in the library contains some imperceptible performance optimizations. For instance, MinmaxElement is done by taking two elements at a time. In this way, the overall number of comparisons is significantly reduced.

There are alternative libraries have similar goals, such as gostl, gods and go-stp. What makes iter unique is:

  • Non-intrusive. Instead of introducing new containers, iter tends to reuse existed containers in Go (slice, string, list.List, etc.) and use iterators to adapt them to algorithms.

  • Full algorithms (>100). It includes almost all algorithms come before C++17. Check the Full List.

Examples

The examples are run with some function alias to make it simple. See example_test.go for the detail.

Print a list.List
l := list.New()
for i := 1; i <= 5; i++ {
  l.PushBack(i)
}
for e := l.Front(); e != nil; e = e.Next() {
  fmt.Print(e.Value)
  if e.Next() != nil {
    fmt.Print("->")
  }
}
// Output:
// 1->2->3->4->5
l := list.New()
GenerateN(ListBackInserter(l), 5, IotaGenerator(1))
Copy(lBegin(l), lEnd(l), IOWriter(os.Stdout, "->"))
// Output:
// 1->2->3->4->5
Reverse a string
s := "!dlrow olleH"
var sb strings.Builder
for i := len(s) - 1; i >= 0; i-- {
  sb.WriteByte(s[i])
}
fmt.Println(sb.String())

b := []byte(s)
for i := len(s)/2 - 1; i >= 0; i-- {
  j := len(s) - 1 - i
  b[i], b[j] = b[j], b[i]
}
fmt.Println(string(b))
// Output:
// Hello world!
// Hello world!
s := "!dlrow olleH"
fmt.Println(MakeString(StringRBegin(s), StringREnd(s)))

b := []byte(s)
Reverse(begin(b), end(b))
fmt.Println(string(b))
// Output:
// Hello world!
// Hello world!
In-place deduplicate (from SliceTricks, with minor change)
in := []int{3, 2, 1, 4, 3, 2, 1, 4, 1}
sort.Ints(in)
j := 0
for i := 1; i < len(in); i++ {
  if in[j] == in[i] {
    continue
  }
  j++
  in[j] = in[i]
}
in = in[:j+1]
fmt.Println(in)
// Output:
// [1 2 3 4]
in := []int{3, 2, 1, 4, 3, 2, 1, 4, 1}
Sort(begin(in), end(in))
Erase(&in, Unique(begin(in), end(in)))
fmt.Println(in)
// Output:
// [1 2 3 4]
Sum all integers received from a channel
ch := make(chan int)
go func() {
  for _, x := range rand.Perm(100) {
    ch <- x + 1
  }
  close(ch)
}()
var sum int
for x := range ch {
  sum += x
}
fmt.Println(sum)
// Output:
// 5050
ch := make(chan int)
go func() {
  CopyN(IotaReader(1), 100, ChanWriter(ch))
  close(ch)
}()
fmt.Println(Accumulate(ChanReader(ch), ChanEOF, 0))
// Output:
// 5050
Remove consecutive spaces in a string
str := "  a  quick   brown  fox  "
var sb strings.Builder
var prevIsSpace bool
for i := 0; i < len(str); i++ {
  if str[i] != ' ' || !prevIsSpace {
    sb.WriteByte(str[i])
  }
  prevIsSpace = str[i] == ' '
}
fmt.Println(sb.String())
// Output:
// a quick brown fox
str := "  a  quick   brown  fox  "
var sb StringBuilderInserter
UniqueCopyIf(sBegin(str), sEnd(str), &sb,
  func(x, y Any) bool { return x.(byte) == ' ' && y.(byte) == ' ' })
fmt.Println(sb.String())
// Output:
// a quick brown fox
Collect N maximum elements from a channel
// Need to manually mantain a min-heap.
top := make([]int, 5)
PartialSortCopyBy(ChanReader(ch), ChanEOF, begin(top), end(top),
  func(x, y Any) bool { return x.(int) > y.(int) })
Copy(begin(top), end(top), IOWriter(os.Stdout, ", "))
Print all permutations of ["a", "b", "c"]
// Usually requires some sort of recursion
s := []string{"a", "b", "c"}
for ok := true; ok; ok = NextPermutation(begin(s), end(s)) {
  fmt.Println(s)
}
// Output:
// [a b c]
// [a c b]
// [b a c]
// [b c a]
// [c a b]
// [c b a]

Thanks

License

BSD 3-Clause

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllOf

func AllOf(first, last InputIter, pred UnaryPredicate) bool

AllOf checks if unary predicate pred returns true for all elements in the range [first, last).

func AnyOf

func AnyOf(first, last InputIter, pred UnaryPredicate) bool

AnyOf checks if unary predicate pred returns true for at least one element in the range [first, last).

func BinarySearch

func BinarySearch(first, last ForwardReader, v Any) bool

BinarySearch checks if an element equivalent to value appears within the range [first, last).

func BinarySearchBy

func BinarySearchBy(first, last ForwardReader, v Any, less LessComparer) bool

BinarySearchBy checks if an element equivalent to value appears within the range [first, last).

Elements are compared using the given binary comparer less.

func Count

func Count(first, last InputIter, v Any) int

Count counts the elements that are equal to value.

func CountIf

func CountIf(first, last InputIter, pred UnaryPredicate) int

CountIf counts elements for which predicate pred returns true.

func Distance

func Distance(first, last Iter) int

Distance returns the distance of two iterators.

func Equal

func Equal(first1, last1, first2, last2 InputIter) bool

Equal returns true if the range [first1, last1) is equal to the range [first2, last2), and false otherwise.

If last2 is nil, it denotes first2 + (last1 - first1).

func EqualBy

func EqualBy(first1, last1, first2, last2 InputIter, eq EqComparer) bool

EqualBy returns true if the range [first1, last1) is equal to the range [first2, last2), and false otherwise.

If last2 is nil, it denotes first2 + (last1 - first1). Elements are compared using the given binary comparer eq.

func EqualRange

func EqualRange(first, last ForwardReader, v Any) (ForwardReader, ForwardReader)

EqualRange returns a range containing all elements equivalent to value in the range [first, last).

func EqualRangeBy

func EqualRangeBy(first, last ForwardReader, v Any, less LessComparer) (ForwardReader, ForwardReader)

EqualRangeBy returns a range containing all elements equivalent to value in the range [first, last).

Elements are compared using the given binary comparer less.

func Erase

func Erase(c interface{}, it ...Iter)

Erase removes a range from a container. c should be settable (*[]T or *list.List). With 2 iterators arguments, it removes [it1, it2). With 1 iterator argument, it removes [it, end). With no iterator argument, it remvoes [begin, end).

func Fill

func Fill(first, last ForwardWriter, v Any)

Fill assigns the given value to the elements in the range [first, last).

func FillN

func FillN(dFirst OutputIter, count int, v Any)

FillN assigns the given value to the first count elements in the range beginning at dFirst.

If count <= 0, it does nothing.

func Generate

func Generate(first, last ForwardWriter, g Generator)

Generate assigns each element in range [first, last) a value generated by the given function object g.

func Includes

func Includes(first1, last1, first2, last2 InputIter) bool

Includes returns true if the sorted range [first2, last2) is a subsequence of the sorted range [first1, last1). (A subsequence need not be contiguous.)

func IncludesBy

func IncludesBy(first1, last1, first2, last2 InputIter, less LessComparer) bool

IncludesBy returns true if the sorted range [first2, last2) is a subsequence of the sorted range [first1, last1). (A subsequence need not be contiguous.)

Elements are compared using the given binary comparer less.

func InplaceMerge

func InplaceMerge(first, middle, last BidiReadWriter)

InplaceMerge Merges two consecutive sorted ranges [first, middle) and [middle, last) into one sorted range [first, last). For equivalent elements in the original two ranges, the elements from the first range (preserving their original order) precede the elements from the second range (preserving their original order).

func InplaceMergeBy

func InplaceMergeBy(first, middle, last BidiReadWriter, less LessComparer)

InplaceMergeBy Merges two consecutive sorted ranges [first, middle) and [middle, last) into one sorted range [first, last). For equivalent elements in the original two ranges, the elements from the first range (preserving their original order) precede the elements from the second range (preserving their original order).

Elements are compared using the given binary comparer less.

func Iota

func Iota(first, last ForwardWriter, v Any)

Iota fills the range [first, last) with sequentially increasing values, starting with v and repetitively evaluating v++/v.Inc().

func IotaBy

func IotaBy(first, last ForwardWriter, v Any, inc UnaryOperation)

IotaBy fills the range [first, last) with sequentially increasing values, starting with v and repetitively evaluating inc(v).

func IsHeap

func IsHeap(first, last RandomReader) bool

IsHeap checks if the elements in range [first, last) are a max heap.

func IsHeapBy

func IsHeapBy(first, last RandomReader, less LessComparer) bool

IsHeapBy checks if the elements in range [first, last) are a max heap.

Elements are compared using the given binary comparer less.

func IsPartitioned

func IsPartitioned(first, last InputIter, pred UnaryPredicate) bool

IsPartitioned returns true if all elements in the range [first, last) that satisfy the predicate pred appear before all elements that don't. Also returns true if [first, last) is empty.

func IsPermutation

func IsPermutation(first1, last1, first2, last2 ForwardReader) bool

IsPermutation returns true if there exists a permutation of the elements in the range [first1, last1) that makes that range equal to the range [first2,last2), where last2 denotes first2 + (last1 - first1) if it was not given.

func IsPermutationBy

func IsPermutationBy(first1, last1, first2, last2 ForwardReader, eq EqComparer) bool

IsPermutationBy returns true if there exists a permutation of the elements in the range [first1, last1) that makes that range equal to the range [first2,last2), where last2 denotes first2 + (last1 - first1) if it was not given.

Elements are compared using the given binary comparer eq.

func IsSorted

func IsSorted(first, last ForwardReader) bool

IsSorted checks if the elements in range [first, last) are sorted in non-descending order.

func IsSortedBy

func IsSortedBy(first, last ForwardReader, less LessComparer) bool

IsSortedBy checks if the elements in range [first, last) are sorted in non-descending order.

Elements are compared using the given binary comparer less.

func LexicographicalCompare

func LexicographicalCompare(first1, last1, first2, last2 InputIter) bool

LexicographicalCompare checks if the first range [first1, last1) is lexicographically less than the second range [first2, last2).

func LexicographicalCompareBy

func LexicographicalCompareBy(first1, last1, first2, last2 InputIter, less LessComparer) bool

LexicographicalCompareBy checks if the first range [first1, last1) is lexicographically less than the second range [first2, last2).

Elements are compared using the given binary comparer less.

func LexicographicalCompareThreeWay

func LexicographicalCompareThreeWay(first1, last1, first2, last2 InputIter) int

LexicographicalCompareThreeWay lexicographically compares two ranges [first1, last1) and [first2, last2) using three-way comparison. The result will be 0 if [first1, last1) == [first2, last2), -1 if [first1, last1) < [first2, last2), 1 if [first1, last1) > [first2, last2).

func LexicographicalCompareThreeWayBy

func LexicographicalCompareThreeWayBy(first1, last1, first2, last2 InputIter, cmp ThreeWayComparer) int

LexicographicalCompareThreeWayBy lexicographically compares two ranges [first1, last1) and [first2, last2) using three-way comparison. The result will be 0 if [first1, last1) == [first2, last2), -1 if [first1, last1) < [first2, last2), 1 if [first1, last1) > [first2, last2).

Elements are compared using the given binary predicate cmp.

func MakeHeap

func MakeHeap(first, last RandomReadWriter)

MakeHeap constructs a max heap in the range [first, last).

func MakeHeapBy

func MakeHeapBy(first, last RandomReadWriter, less LessComparer)

MakeHeapBy constructs a max heap in the range [first, last).

Elements are compared using the given binary comparer less.

func MakeString

func MakeString(first, last ForwardReader) string

MakeString creates a string by range spesified by [first, last). The value type should be byte or rune.

Example

Reverse a string.

s := "!dlrow olleH"
fmt.Println(MakeString(StringRBegin(s), StringREnd(s)))
b := []byte(s)
Reverse(begin(b), end(b))
fmt.Println(string(b))
Output:

Hello world!
Hello world!

func Minmax

func Minmax(a, b Any) (Any, Any)

Minmax returns the smaller and larger of two elements.

func MinmaxBy

func MinmaxBy(a, b Any, less LessComparer) (Any, Any)

MinmaxBy returns the smaller and larger of two elements.

Values are compared using the given binary comparer less.

func MinmaxElement

func MinmaxElement(first, last ForwardReader) (ForwardReader, ForwardReader)

MinmaxElement returns the smallest and the largest elements in a range.

func MinmaxElementBy

func MinmaxElementBy(first, last ForwardReader, less LessComparer) (ForwardReader, ForwardReader)

MinmaxElementBy returns the smallest and the largest elements in a range.

Values are compared using the given binary comparer less.

func Mismatch

func Mismatch(first1, last1, first2, last2 InputIter) (InputIter, InputIter)

Mismatch returns the first mismatching pair of elements from two ranges: one defined by [first1, last1) and another defined by [first2,last2).

If last2 is nil, it denotes first2 + (last1 - first1).

func MismatchBy

func MismatchBy(first1, last1, first2, last2 InputIter, eq EqComparer) (InputIter, InputIter)

MismatchBy returns the first mismatching pair of elements from two ranges: one defined by [first1, last1) and another defined by [first2,last2).

If last2 is nil, it denotes first2 + (last1 - first1). Elements are compared using the given comparer eq.

func NextPermutation

func NextPermutation(first, last BidiReadWriter) bool

NextPermutation transforms the range [first, last) into the next permutation from the set of all permutations that are lexicographically ordered. Returns true if such permutation exists, otherwise transforms the range into the first permutation (as if by Sort(first, last)) and returns false.

Example

Print all permutations of ["a", "b", "c"].

s := []string{"a", "b", "c"}
for ok := true; ok; ok = NextPermutation(begin(s), end(s)) {
	fmt.Println(s)
}
Output:

[a b c]
[a c b]
[b a c]
[b c a]
[c a b]
[c b a]

func NextPermutationBy

func NextPermutationBy(first, last BidiReadWriter, less LessComparer) bool

NextPermutationBy transforms the range [first, last) into the next permutation from the set of all permutations that are lexicographically ordered with respect to less. Returns true if such permutation exists, otherwise transforms the range into the first permutation (as if by Sort(first, last)) and returns false.

Elements are compared using the given binary comparer less.

func NoneOf

func NoneOf(first, last InputIter, pred UnaryPredicate) bool

NoneOf checks if unary predicate pred returns true for no elements in the range [first, last).

func NthElement

func NthElement(first, nth, last RandomReadWriter)

NthElement is a partial sorting algorithm that rearranges elements in [first, last) such that: a. The element pointed at by nth is changed to whatever element would occur in that position if [first, last) were sorted. b. All of the elements before this new nth element are less than or equal to the elements after the new nth element.

func NthElementBy

func NthElementBy(first, nth, last RandomReadWriter, less LessComparer)

NthElementBy is a partial sorting algorithm that rearranges elements in [first, last) such that: a. The element pointed at by nth is changed to whatever element would occur in that position if [first, last) were sorted. b. All of the elements before this new nth element are less than or equal to the elements after the new nth element.

Elements are compared using the given binary comparer less.

func PartialSort

func PartialSort(first, middle, last RandomReadWriter)

PartialSort rearranges elements such that the range [first, middle) contains the sorted (middle-first) smallest elements in the range [first, last).

The order of equal elements is not guaranteed to be preserved. The order of the remaining elements in the range [middle, last) is unspecified.

func PartialSortBy

func PartialSortBy(first, middle, last RandomReadWriter, less LessComparer)

PartialSortBy rearranges elements such that the range [first, middle) contains the sorted (middle-first) smallest elements in the range [first, last).

The order of equal elements is not guaranteed to be preserved. The order of the remaining elements in the range [middle, last) is unspecified. Elements are compared using the given binary comparer less.

func PartialSortCopy

func PartialSortCopy(first, last InputIter, dFirst, dLast RandomReadWriter)

PartialSortCopy sorts some of the elements in the range [first, last) in ascending order, storing the result in the range [dFirst, dLast).

At most dLast - dFirst of the elements are placed sorted to the range [dFirst, dFirst + n). n is the number of elements to sort (n = min(last - first, dLast - dFirst)). The order of equal elements is not guaranteed to be preserved.

func PartialSortCopyBy

func PartialSortCopyBy(first, last InputIter, dFirst, dLast RandomReadWriter, less LessComparer)

PartialSortCopyBy sorts some of the elements in the range [first, last) in ascending order, storing the result in the range [dFirst, dLast).

At most dLast - dFirst of the elements are placed sorted to the range [dFirst, dFirst + n). n is the number of elements to sort (n = min(last - first, dLast - dFirst)). The order of equal elements is not guaranteed to be preserved. Elements are compared using the given binary comparer less.

Example

Collect N maximum elements from a channel.

ch := make(chan int)
go func() {
	n := make([]int, 100)
	Iota(begin(n), end(n), 1)
	Shuffle(begin(n), end(n), r)
	Copy(begin(n), end(n), ChanWriter(ch))
	close(ch)
}()
top := make([]int, 5)
PartialSortCopyBy(ChanReader(ch), ChanEOF, begin(top), end(top),
	func(x, y Any) bool { return x.(int) > y.(int) })
Copy(begin(top), end(top), IOWriter(os.Stdout, ", "))
Output:

100, 99, 98, 97, 96

func PartitionCopy

func PartitionCopy(first, last InputIter, outTrue, outFalse OutputIter, pred UnaryPredicate) (OutputIter, OutputIter)

PartitionCopy copies the elements from the range [first, last) to two different ranges depending on the value returned by the predicate pred. The elements that satisfy the predicate pred are copied to the range beginning at outTrue. The rest of the elements are copied to the range beginning at outFalse.

func PopHeap

func PopHeap(first, last RandomReadWriter)

PopHeap swaps the value in the position first and the value in the position last-1 and makes the subrange [first, last-1) into a heap. This has the effect of removing the first element from the heap defined by the range [first, last).

func PopHeapBy

func PopHeapBy(first, last RandomReadWriter, less LessComparer)

PopHeapBy swaps the value in the position first and the value in the position last-1 and makes the subrange [first, last-1) into a heap. This has the effect of removing the first element from the heap defined by the range [first, last).

Elements are compared using the given binary comparer less.

func PrevPermutation

func PrevPermutation(first, last BidiReadWriter) bool

PrevPermutation transforms the range [first, last) into the previous permutation from the set of all permutations that are lexicographically ordered. Returns true if such permutation exists, otherwise transforms the range into the last permutation (as if by Sort(first, last); Reverse(first, last);) and returns false.

func PrevPermutationBy

func PrevPermutationBy(first, last BidiReadWriter, less LessComparer) bool

PrevPermutationBy transforms the range [first, last) into the previous permutation from the set of all permutations that are lexicographically ordered with respect to less. Returns true if such permutation exists, otherwise transforms the range into the last permutation (as if by Sort(first, last); Reverse(first, last);) and returns false.

Elements are compared using the given binary comparer less.

func PushHeap

func PushHeap(first, last RandomReadWriter)

PushHeap inserts the element at the position last-1 into the max heap defined by the range [first, last-1).

func PushHeapBy

func PushHeapBy(first, last RandomReadWriter, less LessComparer)

PushHeapBy inserts the element at the position last-1 into the max heap defined by the range [first, last-1).

Elements are compared using the given binary comparer less.

func Replace

func Replace(first, last ForwardReadWriter, old, new Any)

Replace replaces all elements equal to old with new in the range [first, last).

func ReplaceIf

func ReplaceIf(first, last ForwardReadWriter, pred UnaryPredicate, v Any)

ReplaceIf replaces all elements satisfy pred with new in the range [first, last).

func Reverse

func Reverse(first, last BidiReadWriter)

Reverse reverses the order of the elements in the range [first, last).

func Shuffle

func Shuffle(first, last RandomReadWriter, r *rand.Rand)

Shuffle reorders the elements in the given range [first, last) such that each possible permutation of those elements has equal probability of appearance.

func Sort

func Sort(first, last RandomReadWriter)

Sort sorts the elements in the range [first, last) in ascending order. The order of equal elements is not guaranteed to be preserved.

func SortBy

func SortBy(first, last RandomReadWriter, less LessComparer)

SortBy sorts the elements in the range [first, last) in ascending order. The order of equal elements is not guaranteed to be preserved.

Elements are compared using the given binary comparer less.

func SortHeap

func SortHeap(first, last RandomReadWriter)

SortHeap converts the max heap [first, last) into a sorted range in ascending order. The resulting range no longer has the heap property.

func SortHeapBy

func SortHeapBy(first, last RandomReadWriter, less LessComparer)

SortHeapBy converts the max heap [first, last) into a sorted range in ascending order. The resulting range no longer has the heap property.

Elements are compared using the given binary comparer less.

func StableSort

func StableSort(first, last RandomReadWriter)

StableSort sorts the elements in the range [first, last) in ascending order. The order of equivalent elements is guaranteed to be preserved.

func StableSortBy

func StableSortBy(first, last RandomReadWriter, less LessComparer)

StableSortBy sorts the elements in the range [first, last) in ascending order.

The order of equivalent elements is guaranteed to be preserved. Elements are compared using the given binary comparer less.

func Swap

func Swap(a, b ReadWriter)

Swap swaps value of two iterators.

func SwapRanges

func SwapRanges(first1, last1, first2 ForwardReadWriter)

SwapRanges exchanges elements between range [first1, last1) and another range starting at first2.

Types

type Any

type Any interface{}

Any represents any type.

func Accumulate

func Accumulate(first, last InputIter, v Any) Any

Accumulate computes the sum of the given value v and the elements in the range [first, last), using v+=x or v=v.Add(x).

func AccumulateBy

func AccumulateBy(first, last InputIter, v Any, add BinaryOperation) Any

AccumulateBy computes the sum of the given value v and the elements in the range [first, last), using v=add(v,x).

func Clamp

func Clamp(v, lo, hi Any) Any

Clamp clamps a value between a pair of boundary values.

func ClampBy

func ClampBy(v, lo, hi Any, less LessComparer) Any

ClampBy clamps a value between a pair of boundary values.

Values are compared using the given binary comparer less.

func InnerProduct

func InnerProduct(first1, last1, first2 InputIter, v Any) Any

InnerProduct computes inner product (i.e. sum of products) or performs ordered map/reduce operation on the range [first1, last1), using v=v+x*y or v=v.Add(x.Mul(y)).

func InnerProductBy

func InnerProductBy(first1, last1, first2 InputIter, v Any, add, mul BinaryOperation) Any

InnerProductBy computes inner product (i.e. sum of products) or performs ordered map/reduce operation on the range [first1, last1), using v=add(v,mul(x,y)).

func Max

func Max(a, b Any) Any

Max returns the greater of the given values.

func MaxBy

func MaxBy(a, b Any, less LessComparer) Any

MaxBy returns the greater of the given values.

Values are compared using the given binary comparer less.

func Min

func Min(a, b Any) Any

Min returns the smaller of the given values.

func MinBy

func MinBy(a, b Any, less LessComparer) Any

MinBy returns the smaller of the given values.

Values are compared using the given binary comparer less.

type BidiIter

type BidiIter interface {
	ForwardIter
	Prev() BidiIter
}

BidiIter is an iterator that moves both forward or backward.

func NextBidiIter

func NextBidiIter(bi BidiIter) BidiIter

NextBidiIter moves a BidiIter to next.

func PrevBidiIter

func PrevBidiIter(bi BidiIter) BidiIter

PrevBidiIter moves a BidiIter to prev.

type BidiReadWriter

type BidiReadWriter interface {
	BidiIter
	ReadWriter
}

BidiReadWriter is an interface that groups BidiIter and ReadWriter.

func ListBegin

func ListBegin(l *list.List) BidiReadWriter

ListBegin returns an iterator to the front element of the list.

func ListEnd

func ListEnd(l *list.List) BidiReadWriter

ListEnd returns an iterator to the passed last element of the list.

func ListRBegin

func ListRBegin(l *list.List) BidiReadWriter

ListRBegin returns an iterator to the back element of the list.

func ListREnd

func ListREnd(l *list.List) BidiReadWriter

ListREnd returns an iterator to the passed first element of the list.

func NextBidiReadWriter

func NextBidiReadWriter(br BidiReadWriter) BidiReadWriter

NextBidiReadWriter moves a BidiReadWriter to next.

func PrevBidiReadWriter

func PrevBidiReadWriter(br BidiReadWriter) BidiReadWriter

PrevBidiReadWriter moves a BidiReadWriter to prev.

type BidiReader

type BidiReader interface {
	BidiIter
	Reader
}

BidiReader is an interface that groups BidiIter and Reader.

func NextBidiReader

func NextBidiReader(br BidiReader) BidiReader

NextBidiReader moves a BidiReader to next.

func PrevBidiReader

func PrevBidiReader(br BidiReader) BidiReader

PrevBidiReader moves a BidiReader to prev.

type BidiWriter

type BidiWriter interface {
	BidiIter
	Writer
}

BidiWriter is an interface that groups BidiIter and Writer.

func CopyBackward

func CopyBackward(first, last BidiReader, dLast BidiWriter) BidiWriter

CopyBackward copies the elements from the range, defined by [first, last), to another range ending at dLast.

The elements are copied in reverse order (the last element is copied first), but their relative order is preserved. It returns an iterator to the last element copied.

func NextBidiWriter

func NextBidiWriter(br BidiWriter) BidiWriter

NextBidiWriter moves a BidiWriter to next.

func PrevBidiWriter

func PrevBidiWriter(br BidiWriter) BidiWriter

PrevBidiWriter moves a BidiWriter to prev.

type BinaryOperation

type BinaryOperation func(Any, Any) Any

BinaryOperation transforms 2 values to 1 value.

type EqComparer

type EqComparer func(Any, Any) bool

EqComparer checks if first value equals to the second value.

type ForwardIter

type ForwardIter interface {
	Incrementable
	Eq(Iter) bool
	AllowMultiplePass() // a marker indicates it can be multiple passed.
}

ForwardIter is an iterator that moves forward.

func NextForwardIter

func NextForwardIter(r ForwardIter) ForwardIter

NextForwardIter moves a ForwardIter to next.

type ForwardReadWriter

type ForwardReadWriter interface {
	ForwardIter
	ReadWriter
}

ForwardReadWriter is an interface that groups ForwardIter and ReadWriter.

func NextForwardReadWriter

func NextForwardReadWriter(rw ForwardReadWriter) ForwardReadWriter

NextForwardReadWriter moves a ForwardReadWriter to next.

func Partition

func Partition(first, last ForwardReadWriter, pred UnaryPredicate) ForwardReadWriter

Partition reorders the elements in the range [first, last) in such a way that all elements for which the predicate pred returns true precede the elements for which predicate pred returns false.

Relative order of the elements is not preserved.

func Remove

func Remove(first, last ForwardReadWriter, v Any) ForwardReadWriter

Remove removes all elements equal to v from the range [first, last) and returns a past-the-end iterator for the new end of the range.

func RemoveIf

func RemoveIf(first, last ForwardReadWriter, pred UnaryPredicate) ForwardReadWriter

RemoveIf removes all elements which predicate function returns true from the range [first, last) and returns a past-the-end iterator for the new end of the range.

func Rotate

func Rotate(first, nFirst, last ForwardReadWriter) ForwardReadWriter

Rotate performs a left rotation on a range of elements in such a way, that the element nFirst becomes the first element of the new range and nFirst - 1 becomes the last element.

func StablePartition

func StablePartition(first, last ForwardReadWriter, pred UnaryPredicate) ForwardReadWriter

StablePartition reorders the elements in the range [first, last) in such a way that all elements for which the predicate pred returns true precede the elements for which predicate pred returns false. Relative order of the elements is preserved.

func Unique

func Unique(first, last ForwardReadWriter) ForwardReadWriter

Unique eliminates all but the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.

Example

Deduplicate elements.

in := []int{3, 2, 1, 4, 3, 2, 1, 4, 1}
Sort(begin(in), end(in))
Erase(&in, Unique(begin(in), end(in)))
fmt.Println(in)
Output:

[1 2 3 4]

func UniqueIf

func UniqueIf(first, last ForwardReadWriter, eq EqComparer) ForwardReadWriter

UniqueIf eliminates all but the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.

Elements are compared using the given binary comparer eq.

type ForwardReader

type ForwardReader interface {
	ForwardIter
	Reader
}

ForwardReader is an interface that groups ForwardIter and Reader.

func AdjacentFind

func AdjacentFind(first, last ForwardReader) ForwardReader

AdjacentFind searches the range [first, last) for two consecutive identical elements.

func AdjacentFindBy

func AdjacentFindBy(first, last ForwardReader, eq EqComparer) ForwardReader

AdjacentFindBy searches the range [first, last) for two consecutive identical elements.

Elements are compared using the given binary comparer eq.

func FindEnd

func FindEnd(first, last, sFirst, sLast ForwardReader) ForwardReader

FindEnd searches for the last occurrence of the sequence [sFirst, sLast) in the range [first, last).

If [sFirst, sLast) is empty or such sequence is found, last is returned.

func FindEndBy

func FindEndBy(first, last, sFirst, sLast ForwardReader, eq EqComparer) ForwardReader

FindEndBy searches for the last occurrence of the sequence [sFirst, sLast) in the range [first, last).

If [sFirst, sLast) is empty or such sequence is found, last is returned. Elements are compared using the given binary comparer eq.

func FindFirstOf

func FindFirstOf(first, last, sFirst, sLast ForwardReader) ForwardReader

FindFirstOf searches the range [first, last) for any of the elements in the range [sFirst, sLast).

func FindFirstOfBy

func FindFirstOfBy(first, last, sFirst, sLast ForwardReader, eq EqComparer) ForwardReader

FindFirstOfBy searches the range [first, last) for any of the elements in the range [sFirst, sLast).

Elements are compared using the given binary comparer eq.

func IsSortedUntil

func IsSortedUntil(first, last ForwardReader) ForwardReader

IsSortedUntil examines the range [first, last) and finds the largest range beginning at first in which the elements are sorted in ascending order.

func IsSortedUntilBy

func IsSortedUntilBy(first, last ForwardReader, less LessComparer) ForwardReader

IsSortedUntilBy examines the range [first, last) and finds the largest range beginning at first in which the elements are sorted in ascending order.

Elements are compared using the given binary comparer less.

func LowerBound

func LowerBound(first, last ForwardReader, v Any) ForwardReader

LowerBound returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value, or last if no such element is found.

func LowerBoundBy

func LowerBoundBy(first, last ForwardReader, v Any, less LessComparer) ForwardReader

LowerBoundBy returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value, or last if no such element is found.

Elements are compared using the given binary comparer less.

func MaxElement

func MaxElement(first, last ForwardReader) ForwardReader

MaxElement returns the largest element in a range.

func MaxElementBy

func MaxElementBy(first, last ForwardReader, less LessComparer) ForwardReader

MaxElementBy returns the largest element in a range.

Values are compared using the given binary comparer less.

func MinElement

func MinElement(first, last ForwardReader) ForwardReader

MinElement returns the smallest element in a range.

func MinElementBy

func MinElementBy(first, last ForwardReader, less LessComparer) ForwardReader

MinElementBy returns the smallest element in a range.

Values are compared using the given binary comparer less.

func NextForwardReader

func NextForwardReader(r ForwardReader) ForwardReader

NextForwardReader moves a ForwardReader to next.

func PartitionPoint

func PartitionPoint(first, last ForwardReader, pred UnaryPredicate) ForwardReader

PartitionPoint examines the partitioned (as if by Partition) range [first, last) and locates the end of the first partition, that is, the first element that does not satisfy pred or last if all elements satisfy pred.

func Search(first, last, sFirst, sLast ForwardReader) ForwardReader

Search searches for the first occurrence of the sequence of elements [sFirst, sLast) in the range [first, last).

func SearchBy

func SearchBy(first, last, sFirst, sLast ForwardReader, eq EqComparer) ForwardReader

SearchBy searches for the first occurrence of the sequence of elements [sFirst, sLast) in the range [first, last).

Elements are compared using the given binary comparer eq.

func SearchN

func SearchN(first, last ForwardReader, count int, v Any) ForwardReader

SearchN searches the range [first, last) for the first sequence of count identical elements, each equal to the given value.

func SearchNBy

func SearchNBy(first, last ForwardReader, count int, v Any, eq EqComparer) ForwardReader

SearchNBy searches the range [first, last) for the first sequence of count identical elements.

Elements are compared using the given binary comparer eq.

func UpperBound

func UpperBound(first, last ForwardReader, v Any) ForwardReader

UpperBound returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found.

func UpperBoundBy

func UpperBoundBy(first, last ForwardReader, v Any, less LessComparer) ForwardReader

UpperBoundBy returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found.

Elements are compared using the given binary comparer less.

type ForwardWriter

type ForwardWriter interface {
	ForwardIter
	Writer
}

ForwardWriter is an interface that groups ForwardIter and Writer.

func NextForwardWriter

func NextForwardWriter(w ForwardWriter) ForwardWriter

NextForwardWriter moves a ForwardWriter to next.

type Generator

type Generator func() Any

Generator creates a value on each call.

func IotaGenerator

func IotaGenerator(x Any) Generator

IotaGenerator creates a Generator that returns [x, x+1, x+2...).

func RandomGenerator

func RandomGenerator(s interface{}, r *rand.Rand) Generator

RandomGenerator creates a generator that returns random item of a slice.

func RepeatGenerator

func RepeatGenerator(x Any) Generator

RepeatGenerator creates an Generator that returns [x, x, x...).

type Incrementable

type Incrementable interface {
	Next() Incrementable
}

Incrementable represents iterators that can move forward.

type InputIter

type InputIter interface {
	Reader
	Incrementable
	Eq(Iter) bool
}

InputIter is a readable and incrementable iterator.

var ChanEOF InputIter = eof(0)

ChanEOF is a sentinel iterator to terminate chan reader.

func ChanReader

func ChanReader(c interface{}) InputIter

ChanReader returns an InputIter that reads from a channel.

Example

Sum all integers received from a channel.

ch := make(chan int)
go func() {
	CopyN(IotaReader(1), 100, ChanWriter(ch))
	close(ch)
}()
fmt.Println(Accumulate(ChanReader(ch), ChanEOF, 0))
Output:

5050

func Find

func Find(first, last InputIter, v Any) InputIter

Find returns the first element in the range [first, last) that is equal to value.

func FindIf

func FindIf(first, last InputIter, pred UnaryPredicate) InputIter

FindIf returns the first element in the range [first, last) which predicate pred returns true.

func FindIfNot

func FindIfNot(first, last InputIter, pred UnaryPredicate) InputIter

FindIfNot returns the first element in the range [first, last) which predicate pred returns false.

func IotaReader

func IotaReader(x Any) InputIter

IotaReader creates an InputIter that returns [x, x+1, x+2...).

func NextInputIter

func NextInputIter(it InputIter) InputIter

NextInputIter moves an InputIter forward.

func RepeatReader

func RepeatReader(x Any) InputIter

RepeatReader creates an InputIter that returns [x, x, x...).

type Iter

type Iter = Any

Iter represents an iterator, just an alias of Any.

func AdvanceN

func AdvanceN(it Iter, n int) Iter

AdvanceN moves an iterator by step N.

type IteratorFunction

type IteratorFunction func(Any)

IteratorFunction apply some actions to a value.

func ForEach

func ForEach(first, last InputIter, f IteratorFunction) IteratorFunction

ForEach applies the given function f to the result of dereferencing every iterator in the range [first, last), in order.

func ForEachN

func ForEachN(first InputIter, n int, f IteratorFunction) IteratorFunction

ForEachN applies the given function f to the result of dereferencing every iterator in the range [first, first + n), in order.

type LessComparer

type LessComparer func(Any, Any) bool

LessComparer checks if first value is less than the second value.

type OutputIter

type OutputIter = Writer

OutputIter is a writable and incrementable iterator.

It may not implement the incremental interface, in which case the increment logic is done in Write().

func AdjacentDifference

func AdjacentDifference(first, last InputIter, dFirst OutputIter) OutputIter

AdjacentDifference computes the differences between the second and the first of each adjacent pair of elements of the range [first, last) and writes them to the range beginning at dFirst + 1. An unmodified copy of first is written to dFirst. Differences are calculated by cur-prev or cur.Sub(prev).

func AdjacentDifferenceBy

func AdjacentDifferenceBy(first, last InputIter, dFirst OutputIter, sub BinaryOperation) OutputIter

AdjacentDifferenceBy computes the differences between the second and the first of each adjacent pair of elements of the range [first, last) and writes them to the range beginning at dFirst + 1. An unmodified copy of first is written to dFirst. Differences are calculated by sub(cur,prev).

func ChanWriter

func ChanWriter(c interface{}) OutputIter

ChanWriter returns an OutIter that writes to a channel.

func Copy

func Copy(first, last InputIter, dFirst OutputIter) OutputIter

Copy copies the elements in the range, defined by [first, last), to another range beginning at dFirst.

It returns an iterator in the destination range, pointing past the last element copied.

func CopyIf

func CopyIf(first, last InputIter, dFirst OutputIter, pred UnaryPredicate) OutputIter

CopyIf copies the elements in the range, defined by [first, last), and predicate pred returns true, to another range beginning at dFirst.

It returns an iterator in the destination range, pointing past the last element copied.

func CopyN

func CopyN(first InputIter, count int, dFirst OutputIter) OutputIter

CopyN copies exactly count values from the range beginning at first to the range beginning at dFirst.

It returns an iterator in the destination range, pointing past the last element copied.

func ExclusiveScan

func ExclusiveScan(first, last InputIter, dFirst OutputIter, v Any) OutputIter

ExclusiveScan computes an exclusive prefix sum operation using v=v+cur or v=v.Add(cur) for the range [first, last), using v as the initial value, and writes the results to the range beginning at dFirst. "exclusive" means that the i-th input element is not included in the i-th sum.

func ExclusiveScanBy

func ExclusiveScanBy(first, last InputIter, dFirst OutputIter, v Any, add BinaryOperation) OutputIter

ExclusiveScanBy computes an exclusive prefix sum operation using v=add(v,cur) for the range [first, last), using v as the initial value, and writes the results to the range beginning at dFirst. "exclusive" means that the i-th input element is not included in the i-th sum.

func GenerateN

func GenerateN(dFirst OutputIter, count int, g Generator) OutputIter

GenerateN assigns values, generated by given function object g, to the first count elements in the range beginning at dFirst.

If count <= 0, it does nothing.

func IOWriter

func IOWriter(w io.Writer, delimiter string) OutputIter

IOWriter returns an OutputIter that writes values to an io.Writer. It panics if meet any error.

Example

Print all list items to console.

l := list.New()
GenerateN(ListBackInserter(l), 5, IotaGenerator(1))
Copy(lBegin(l), lEnd(l), IOWriter(os.Stdout, "->"))
Output:

1->2->3->4->5

func InclusiveScan

func InclusiveScan(first, last InputIter, dFirst OutputIter, v Any) OutputIter

InclusiveScan computes an inclusive prefix sum operation using v=v+cur or v=v.Add(cur) for the range [first, last), using v as the initial value (if provided), and writes the results to the range beginning at dFirst. "inclusive" means that the i-th input element is included in the i-th sum.

func InclusiveScanBy

func InclusiveScanBy(first, last InputIter, dFirst OutputIter, v Any, add BinaryOperation) OutputIter

InclusiveScanBy computes an inclusive prefix sum operation using v=add(v,cur) for the range [first, last), using v as the initial value (if provided), and writes the results to the range beginning at dFirst. "inclusive" means that the i-th input element is included in the i-th sum.

func ListBackInserter

func ListBackInserter(l *list.List) OutputIter

ListBackInserter returns an OutputIter to insert elements to the back of the list.

func ListInserter

func ListInserter(l *list.List, e *list.Element) OutputIter

ListInserter returns an OutputIter to insert elements before a node.

func Merge

func Merge(first1, last1, first2, last2 InputIter, dFirst OutputIter) OutputIter

Merge merges two sorted ranges [first1, last1) and [first2, last2) into one sorted range beginning at dFirst.

func MergeBy

func MergeBy(first1, last1, first2, last2 InputIter, dFirst OutputIter, less LessComparer) OutputIter

MergeBy merges two sorted ranges [first1, last1) and [first2, last2) into one sorted range beginning at dFirst.

Elements are compared using the given binary comparer less.

func PartialSum

func PartialSum(first, last InputIter, dFirst OutputIter) OutputIter

PartialSum computes the partial sums of the elements in the subranges of the range [first, last) and writes them to the range beginning at dFirst. Sums are calculated by sum=sum+cur or sum=sum.Add(cur).

func PartialSumBy

func PartialSumBy(first, last InputIter, dFirst OutputIter, add BinaryOperation) OutputIter

PartialSumBy computes the partial sums of the elements in the subranges of the range [first, last) and writes them to the range beginning at dFirst. Sums are calculated by sum=add(sum,cur).

func RemoveCopy

func RemoveCopy(first, last InputIter, dFirst OutputIter, v Any) OutputIter

RemoveCopy copies elements from the range [first, last), to another range beginning at dFirst, omitting the elements equal to v.

Source and destination ranges cannot overlap.

func RemoveCopyIf

func RemoveCopyIf(first, last InputIter, dFirst OutputIter, pred UnaryPredicate) OutputIter

RemoveCopyIf copies elements from the range [first, last), to another range beginning at dFirst, omitting the elements which predicate function returns true.

Source and destination ranges cannot overlap.

func ReplaceCopy

func ReplaceCopy(first, last InputIter, dFirst OutputIter, old, new Any) OutputIter

ReplaceCopy copies the elements from the range [first, last) to another range beginning at dFirst replacing all elements equal to old with new.

The source and destination ranges cannot overlap.

func ReplaceCopyIf

func ReplaceCopyIf(first, last InputIter, dFirst OutputIter, pred UnaryPredicate, v Any) OutputIter

ReplaceCopyIf copies the elements from the range [first, last) to another range beginning at dFirst replacing all elements satisfy pred with new.

The source and destination ranges cannot overlap.

func ReverseCopy

func ReverseCopy(first, last BidiReader, dFirst OutputIter) OutputIter

ReverseCopy copies the elements from the range [first, last) to another range beginning at dFirst in such a way that the elements in the new range are in reverse order.

func RotateCopy

func RotateCopy(first, nFirst, last ForwardReader, dFirst OutputIter) OutputIter

RotateCopy copies the elements from the range [first, last), to another range beginning at dFirst in such a way, that the element nFirst becomes the first element of the new range and nFirst - 1 becomes the last element.

func Sample

func Sample(first, last ForwardReader, out OutputIter, n int, r *rand.Rand) OutputIter

Sample selects n elements from the sequence [first; last) such that each possible sample has equal probability of appearance, and writes those selected elements into the output iterator out.

func SetDifference

func SetDifference(first1, last1, first2, last2 InputIter, dFirst OutputIter) OutputIter

SetDifference copies the elements from the sorted range [first1, last1) which are not found in the sorted range [first2, last2) to the range beginning at dFirst.

func SetDifferenceBy

func SetDifferenceBy(first1, last1, first2, last2 InputIter, dFirst OutputIter, less LessComparer) OutputIter

SetDifferenceBy copies the elements from the sorted range [first1, last1) which are not found in the sorted range [first2, last2) to the range beginning at dFirst.

Elements are compared using the given binary comparer less.

func SetIntersection

func SetIntersection(first1, last1, first2, last2 InputIter, dFirst OutputIter) OutputIter

SetIntersection constructs a sorted range beginning at dFirst consisting of elements that are found in both sorted ranges [first1, last1) and [first2, last2). If some element is found m times in [first1, last1) and n times in [first2, last2), the first Min(m, n) elements will be copied from the first range to the destination range.

The order of equivalent elements is preserved. The resulting range cannot overlap with either of the input ranges.

func SetIntersectionBy

func SetIntersectionBy(first1, last1, first2, last2 InputIter, dFirst OutputIter, less LessComparer) OutputIter

SetIntersectionBy constructs a sorted range beginning at dFirst consisting of elements that are found in both sorted ranges [first1, last1) and [first2, last2). If some element is found m times in [first1, last1) and n times in [first2, last2), the first Min(m, n) elements will be copied from the first range to the destination range.

The order of equivalent elements is preserved. The resulting range cannot overlap with either of the input ranges. Elements are compared using the given binary comparer less.

func SetSymmetricDifference

func SetSymmetricDifference(first1, last1, first2, last2 InputIter, dFirst OutputIter) OutputIter

SetSymmetricDifference computes symmetric difference of two sorted ranges: the elements that are found in either of the ranges, but not in both of them are copied to the range beginning at dFirst. The resulting range is also sorted.

If some element is found m times in [first1, last1) and n times in [first2, last2), it will be copied to dFirst exactly Abs(m-n) times. If m>n, then the last m-n of those elements are copied from [first1,last1), otherwise the last n-m elements are copied from [first2,last2). The resulting range cannot overlap with either of the input ranges.

func SetSymmetricDifferenceBy

func SetSymmetricDifferenceBy(first1, last1, first2, last2 InputIter, dFirst OutputIter, less LessComparer) OutputIter

SetSymmetricDifferenceBy computes symmetric difference of two sorted ranges: the elements that are found in either of the ranges, but not in both of them are copied to the range beginning at dFirst. The resulting range is also sorted.

If some element is found m times in [first1, last1) and n times in [first2, last2), it will be copied to dFirst exactly Abs(m-n) times. If m>n, then the last m-n of those elements are copied from [first1,last1), otherwise the last n-m elements are copied from [first2,last2). The resulting range cannot overlap with either of the input ranges. Elements are compared using the given binary comparer less.

func SetUnion

func SetUnion(first1, last1, first2, last2 InputIter, dFirst OutputIter) OutputIter

SetUnion constructs a sorted union beginning at dFirst consisting of the set of elements present in one or both sorted ranges [first1, last1) and [first2, last2).

If some element is found m times in [first1, last1) and n times in [first2, last2), then all m elements will be copied from [first1, last1) to dFirst, preserving order, and then exactly Max(n-m, 0) elements will be copied from [first2, last2) to dFirst, also preserving order.

func SetUnionBy

func SetUnionBy(first1, last1, first2, last2 InputIter, dFirst OutputIter, less LessComparer) OutputIter

SetUnionBy constructs a sorted union beginning at dFirst consisting of the set of elements present in one or both sorted ranges [first1, last1) and [first2, last2).

If some element is found m times in [first1, last1) and n times in [first2, last2), then all m elements will be copied from [first1, last1) to dFirst, preserving order, and then exactly Max(n-m, 0) elements will be copied from [first2, last2) to dFirst, also preserving order. Elements are compared using the given binary comparer less.

func SliceBackInserter

func SliceBackInserter(s interface{}) OutputIter

SliceBackInserter returns an OutputIter to append elements to the back of the slice.

func Transform

func Transform(first, last InputIter, dFirst OutputIter, op UnaryOperation) OutputIter

Transform applies the given function to the range [first, last) and stores the result in another range, beginning at dFirst.

func TransformBinary

func TransformBinary(first1, last1, first2 ForwardReader, dFirst OutputIter, op BinaryOperation) OutputIter

TransformBinary applies the given function to the two ranges [first, last), [first2, first2+last-first) and stores the result in another range, beginning at dFirst.

func TransformExclusiveScan

func TransformExclusiveScan(first, last InputIter, dFirst OutputIter, v Any, op UnaryOperation) OutputIter

TransformExclusiveScan transforms each element in the range [first, last) with op, then computes an exclusive prefix sum operation using v=v+cur or v=v.Add(cur) for the range [first, last), using v as the initial value, and writes the results to the range beginning at dFirst. "exclusive" means that the i-th input element is not included in the i-th sum.

func TransformExclusiveScanBy

func TransformExclusiveScanBy(first, last InputIter, dFirst OutputIter, v Any, add BinaryOperation, op UnaryOperation) OutputIter

TransformExclusiveScanBy transforms each element in the range [first, last) with op, then computes an exclusive prefix sum operation using v=add(v,cur) for the range [first, last), using v as the initial value, and writes the results to the range beginning at dFirst. "exclusive" means that the i-th input element is not included in the i-th sum.

func TransformInclusiveScan

func TransformInclusiveScan(first, last InputIter, dFirst OutputIter, v Any, op UnaryOperation) OutputIter

TransformInclusiveScan transforms each element in the range [first, last) with op, then computes an inclusive prefix sum operation using v=v+cur or v=v.Add(cur) for the range [first, last), using v as the initial value (if provided), and writes the results to the range beginning at dFirst. "inclusive" means that the i-th input element is included in the i-th sum.

func TransformInclusiveScanBy

func TransformInclusiveScanBy(first, last InputIter, dFirst OutputIter, v Any, add BinaryOperation, op UnaryOperation) OutputIter

TransformInclusiveScanBy transforms each element in the range [first, last) with op, then computes an inclusive prefix sum operation using v=add(v,cur) for the range [first, last), using v as the initial value (if provided), and writes the results to the range beginning at dFirst. "inclusive" means that the i-th input element is included in the i-th sum.

func UniqueCopy

func UniqueCopy(first, last InputIter, dFirst OutputIter) OutputIter

UniqueCopy copies the elements from the range [first, last), to another range beginning at dFirst in such a way that there are no consecutive equal elements.

Only the first element of each group of equal elements is copied.

func UniqueCopyIf

func UniqueCopyIf(first, last InputIter, dFirst OutputIter, eq EqComparer) OutputIter

UniqueCopyIf copies the elements from the range [first, last), to another range beginning at dFirst in such a way that there are no consecutive equal elements.

Only the first element of each group of equal elements is copied. Elements are compared using the given binary comparer eq.

Example

Remove consecutive spaces in a string.

str := "  a  quick   brown  fox  "
var sb StringBuilderInserter
UniqueCopyIf(sBegin(str), sEnd(str), &sb,
	func(x, y Any) bool { return x.(byte) == ' ' && y.(byte) == ' ' })
fmt.Println(sb.String())
Output:

a quick brown fox

type RandomIter

type RandomIter interface {
	BidiIter
	AdvanceN(n int) RandomIter
	Distance(RandomIter) int
	Less(Iter) bool
}

RandomIter is a random access iterator.

func NextRandomIter

func NextRandomIter(bi RandomIter) RandomIter

NextRandomIter moves a RandomIter to next.

func PrevRandomIter

func PrevRandomIter(bi RandomIter) RandomIter

PrevRandomIter moves a RandomIter to prev.

type RandomReadWriter

type RandomReadWriter interface {
	RandomIter
	ReadWriter
}

RandomReadWriter is an interface that groups RandomIter and ReadWriter.

func AdvanceNReadWriter

func AdvanceNReadWriter(rw RandomReadWriter, n int) RandomReadWriter

AdvanceNReadWriter moves a RandomReadWriter by step N.

func NextRandomReadWriter

func NextRandomReadWriter(br RandomReadWriter) RandomReadWriter

NextRandomReadWriter moves a RandomReadWriter to next.

func PrevRandomReadWriter

func PrevRandomReadWriter(br RandomReadWriter) RandomReadWriter

PrevRandomReadWriter moves a RandomReadWriter to prev.

func SliceBegin

func SliceBegin(s interface{}) RandomReadWriter

SliceBegin returns an iterator to the front element of the slice.

func SliceEnd

func SliceEnd(s interface{}) RandomReadWriter

SliceEnd returns an iterator to the passed last element of the slice.

func SliceRBegin

func SliceRBegin(s interface{}) RandomReadWriter

SliceRBegin returns an iterator to the back element of the slice.

func SliceREnd

func SliceREnd(s interface{}) RandomReadWriter

SliceREnd returns an iterator to the passed first element of the slice.

type RandomReader

type RandomReader interface {
	RandomIter
	Reader
}

RandomReader is an interface that groups RandomIter and Reader.

func AdvanceNReader

func AdvanceNReader(rr RandomReader, n int) RandomReader

AdvanceNReader moves a RandomReader by step N.

func IsHeapUntil

func IsHeapUntil(first, last RandomReader) RandomReader

IsHeapUntil examines the range [first, last) and finds the largest range beginning at first which is a max heap.

func IsHeapUntilBy

func IsHeapUntilBy(first, last RandomReader, less LessComparer) RandomReader

IsHeapUntilBy examines the range [first, last) and finds the largest range beginning at first which is a max heap.

Elements are compared using the given binary comparer less.

func NextRandomReader

func NextRandomReader(br RandomReader) RandomReader

NextRandomReader moves a RandomReader to next.

func PrevRandomReader

func PrevRandomReader(br RandomReader) RandomReader

PrevRandomReader moves a RandomReader to prev.

func StringBegin

func StringBegin(s string) RandomReader

StringBegin returns an iterator to the front element of the string.

func StringEnd

func StringEnd(s string) RandomReader

StringEnd returns an iterator to the passed last element of the string.

func StringRBegin

func StringRBegin(s string) RandomReader

StringRBegin returns an iterator to the back element of the string.

func StringREnd

func StringREnd(s string) RandomReader

StringREnd returns an iterator to the passed first element of the string.

type RandomWriter

type RandomWriter interface {
	RandomIter
	Writer
}

RandomWriter is an interface that groups RandomIter and Writer.

func AdvanceNWriter

func AdvanceNWriter(rw RandomWriter, n int) RandomWriter

AdvanceNWriter moves a RandomWriter by step N.

func NextRandomWriter

func NextRandomWriter(br RandomWriter) RandomWriter

NextRandomWriter moves a RandomWriter to next.

func PrevRandomWriter

func PrevRandomWriter(br RandomWriter) RandomWriter

PrevRandomWriter moves a RandomWriter to prev.

type ReadWriter

type ReadWriter interface {
	Reader
	Writer
}

ReadWriter is an interface that groups Reader and Writer.

type Reader

type Reader interface {
	Read() Any
}

Reader is a readable iterator.

type StringBuilderInserter

type StringBuilderInserter struct {
	strings.Builder
	Delimiter string
}

StringBuilderInserter is an OutputIter that wraps a strings.Builder.

func (*StringBuilderInserter) Write

func (si *StringBuilderInserter) Write(x Any)

type ThreeWayComparer

type ThreeWayComparer func(Any, Any) int

ThreeWayComparer compares 2 values, returns 1 if first>second, 0 if first=second, -1 if first<second.

type UnaryOperation

type UnaryOperation func(Any) Any

UnaryOperation transforms a value to another.

type UnaryPredicate

type UnaryPredicate func(Any) bool

UnaryPredicate checks if a value satisfy condition.

type Writer

type Writer interface {
	Write(Any)
}

Writer is a writable iterator.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL