flinx

package module
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: May 10, 2024 License: Apache-2.0 Imports: 5 Imported by: 1

README

go-flinx

Functional LINQ IN Go

Sourcegraph GoDoc Build Status codecov rcard License

Thanks ahmetb/go-linq for a guidance.

Rewrite ahmetb/go-linq for these reasons:

  1. Not compatible with generics. I've been enough to use type assertions.
  2. Low performance when use generic function. You could use generic through function ends with 't', but it's not that efficient and not that elegant.

So to solve my problems, I choose to rewrite it using generics and functional-programing. You know that generics in Go is not that flexible, but feature of Currying and Lazy Evaluation could make this.

Installation

When used with Go modules, use the following import path:

go get github.com/kom0055/go-flinx

Quickstart

If you were a dotNet/C# developer but a gopher now, you must miss the smooth grammar of LINQ.

If you were a fans of functional-programing but a gopher now, you must be eager to code in functional style.

Now, you could both enjoy LINQ and functional-programing through this package.

A simple case like below

squares := ToSlice(Select(func (x int) int { return x * x })(Range(1, 10)))

For more cases, you could visit example_test.go

Performance

Using ahmetb's go-linq comparison benchmark (see benchmark_test.go, test size was 10000000):

SelectWhereFirst:

Lib Time
go-flinx 153.4 ns/op
go-linq 162.6 ns/op
gp-linq(generics func) 1043 ns/op

Sum:

Lib Time
go-flinx 31092617 ns/op
go-linq 119863792 ns/op
gp-linq(generics func) 2249057541 ns/op

ZipSkipTake:

Lib Time
go-flinx 120.3 ns/op
go-linq 108.4 ns/op
gp-linq(generics func) 562.8 ns/op

FromChannel:

Lib Time
go-flinx 1206086167 ns/op
go-linq 1312612709 ns/op
gp-linq(from channelt) 1975103125 ns/op

We could make conclusion that if you chase for efficient performance and elegant grammar, go-flinx is a good choice.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Aggregate

func Aggregate[T any](f func(T, T) T) func(q Query[T]) T

Aggregate applies an accumulator function over a sequence.

Aggregate method makes it simple to perform a calculation over a sequence of values. This method works by calling f() one time for each element in source except the first one. Each time f() is called, Aggregate passes both the element from the sequence and an aggregated value (as the first argument to f()). The first element of source is used as the initial aggregate value. The result of f() replaces the previous aggregated value.

Aggregate returns the final result of f().

func AggregateWithSeed

func AggregateWithSeed[T any](seed T, f func(T, T) T) func(q Query[T]) (t T)

AggregateWithSeed applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value.

Aggregate method makes it simple to perform a calculation over a sequence of values. This method works by calling f() one time for each element in source except the first one. Each time f() is called, Aggregate passes both the element from the sequence and an aggregated value (as the first argument to f()). The value of the seed parameter is used as the initial aggregate value. The result of f() replaces the previous aggregated value.

Aggregate returns the final result of f().

func AggregateWithSeedBy

func AggregateWithSeedBy[T any, V any](seed T, f func(T, T) T, resultSelector func(T) V) func(q Query[T]) (v V)

AggregateWithSeedBy applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value.

Aggregate method makes it simple to perform a calculation over a sequence of values. This method works by calling f() one time for each element in source. Each time func is called, Aggregate passes both the element from the sequence and an aggregated value (as the first argument to func). The value of the seed parameter is used as the initial aggregate value. The result of func replaces the previous aggregated value.

The final result of func is passed to resultSelector to obtain the final result of Aggregate.

func All

func All[T any](predicates ...func(T) bool) func(q Query[T]) bool

All determines whether all elements of a collection satisfy a condition.

func Any

func Any[T any](q Query[T]) bool

Any determines whether any element of a collection exists.

func AnyWith

func AnyWith[T any](predicates ...func(T) bool) func(q Query[T]) bool

AnyWith determines whether any element of a collection satisfies a condition.

func Average

func Average[T constraints.Integer | constraints.Float](q Query[T]) (r float64)

Average computes the average of a collection of numeric values.

func Contains

func Contains[T comparable](value T) func(q Query[T]) bool

Contains determines whether a collection contains a specified element.

func Count

func Count[T any](q Query[T]) (r int)

Count returns the number of elements in a collection.

func CountWith

func CountWith[T any](predicates ...func(T) bool) func(q Query[T]) (r int)

CountWith returns a number that represents how many elements in the specified collection satisfy a condition.

func DistinctBy

func DistinctBy[T any, V comparable](selector func(T) V) func(q Query[T]) Query[T]

DistinctBy method returns distinct elements from a collection. This method executes selector function for each element to determine a value to compare. The result is an unordered collection that contains no duplicate values.

func Eq added in v0.0.7

func Eq[T comparable](v T) func(t T) bool

func ExceptBy

func ExceptBy[T any, V comparable](selector func(T) V) func(q, q2 Query[T]) Query[T]

ExceptBy invokes a transform function on each element of a collection and produces the set difference of two sequences. The set difference is the members of the first sequence that don't appear in the second sequence.

func First

func First[T any](q Query[T]) (T, bool)

First returns the first element of a collection.

func FirstWith

func FirstWith[T any](predicates ...func(T) bool) func(q Query[T]) (T, bool)

FirstWith returns the first element of a collection that satisfies a specified condition.

func ForEach

func ForEach[T any](action func(T)) func(q Query[T])

ForEach performs the specified action on each element of a collection.

func ForEachIndexed

func ForEachIndexed[T any](action func(int, T)) func(q Query[T])

ForEachIndexed performs the specified action on each element of a collection.

The first argument to action represents the zero-based index of that element in the source collection. This can be useful if the elements are in a known order and you want to do something with an element at a particular index, for example. It can also be useful if you want to retrieve the index of one or more elements. The second argument to action represents the element to process.

func GroupBy

func GroupBy[T any, K comparable, V any](keySelector func(T) K,
	elementSelector func(T) V) func(q Query[T]) Query[Group[K, V]]

GroupBy method groups the elements of a collection according to a specified key selector function and projects the elements for each group by using a specified function.

func GroupJoin

func GroupJoin[T, V, O any, K comparable](
	outerKeySelector func(T) K,
	innerKeySelector func(V) K,
	resultSelector func(outer T, inners []V) O) func(q Query[T], inner Query[V]) Query[O]

GroupJoin correlates the elements of two collections based on key equality, and groups the results.

This method produces hierarchical results, which means that elements from outer query are paired with collections of matching elements from inner. GroupJoin enables you to base your results on a whole set of matches for each element of outer query.

The resultSelector function is called only one time for each outer element together with a collection of all the inner elements that match the outer element. This differs from the Join method, in which the result selector function is invoked on pairs that contain one element from outer and one element from inner.

GroupJoin preserves the order of the elements of outer, and for each element of outer, the order of the matching elements from inner.

func Gt added in v0.0.7

func Gt[T constraints.Ordered](v T) func(t T) bool

func Gte added in v0.0.7

func Gte[T constraints.Ordered](v T) func(t T) bool

func In added in v0.0.7

func In[T comparable](v ...T) func(t T) bool

func IndexOf

func IndexOf[T any](predicates ...func(T) bool) func(q Query[T]) int

IndexOf searches for an element that matches the conditions defined by a specified predicate and returns the zero-based index of the first occurrence within the collection. This method returns -1 if an item that matches the conditions is not found.

func IntersectBy

func IntersectBy[T any, V comparable](selector func(T) V) func(q, q2 Query[T]) Query[T]

IntersectBy produces the set intersection of the source collection and the provided input collection. The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.

IntersectBy invokes a transform function on each element of both collections.

func Join

func Join[T, V, Q any, K comparable](
	outerKeySelector func(T) K,
	innerKeySelector func(V) K,
	resultSelector func(outer T, inner V) Q) func(q Query[T], inner Query[V]) Query[Q]

Join correlates the elements of two collection based on matching keys.

A join refers to the operation of correlating the elements of two sources of information based on a common key. Join brings the two information sources and the keys by which they are matched together in one method call. This differs from the use of SelectMany, which requires more than one method call to perform the same operation.

Join preserves the order of the elements of outer collection, and for each of these elements, the order of the matching elements of inner.

func Last

func Last[T any](q Query[T]) (r T, exist bool)

Last returns the last element of a collection.

func LastWith

func LastWith[T any](predicates ...func(T) bool) func(q Query[T]) (r T, exist bool)

LastWith returns the last element of a collection that satisfies a specified condition.

func Lt added in v0.0.7

func Lt[T constraints.Ordered](v T) func(t T) bool

func Lte added in v0.0.7

func Lte[T constraints.Ordered](v T) func(t T) bool

func Max

func Max[T any](compare func(t1, t2 T) int) func(q Query[T]) (r T, exist bool)

Max returns the maximum value in a collection of values.

func Min

func Min[T any](compare func(t1, t2 T) int) func(q Query[T]) (r T, exist bool)

Min returns the minimum value in a collection of values.

func Neq added in v0.0.7

func Neq[T comparable](v T) func(t T) bool

func Nil added in v0.0.6

func Nil(t any) bool

func NonNil added in v0.0.6

func NonNil(t any) bool

func Not added in v0.0.4

func Not[T any](predicate func(T) bool) func(T) bool

func NotIn added in v0.0.7

func NotIn[T comparable](v ...T) func(t T) bool

func OrderBy

func OrderBy[T, V any](compare func(V, V) int, selector func(T) V) func(q Query[T]) OrderedQuery[T]

OrderBy sorts the elements of a collection in ascending order. Elements are sorted according to a key.

func OrderByDescending

func OrderByDescending[T, V any](compare func(V, V) int, selector func(T) V) func(q Query[T]) OrderedQuery[T]

OrderByDescending sorts the elements of a collection in descending order. Elements are sorted according to a key.

func Predicates added in v0.0.9

func Predicates[T any](predicates ...func(T) bool) func(T) bool

func PredicatesIndexed added in v0.0.9

func PredicatesIndexed[T any](predicates ...func(int, T) bool) func(int, T) bool

func Results

func Results[T any](q Query[T]) (r []T)

Results iterates over a collection and returnes slice of interfaces

func Select

func Select[T, V any](selector func(T) V) func(q Query[T]) Query[V]

Select projects each element of a collection into a new form. Returns a query with the result of invoking the transform function on each element of original source.

This projection method requires the transform function, selector, to produce one value for each value in the source collection. If selector returns a value that is itself a collection, it is up to the consumer to traverse the subcollections manually. In such a situation, it might be better for your query to return a single coalesced collection of values. To achieve this, use the SelectMany method instead of Select. Although SelectMany works similarly to Select, it differs in that the transform function returns a collection that is then expanded by SelectMany before it is returned.

func SelectIndexed

func SelectIndexed[T, V any](selector func(int, T) V) func(q Query[T]) Query[V]

SelectIndexed projects each element of a collection into a new form by incorporating the element's index. Returns a query with the result of invoking the transform function on each element of original source.

The first argument to selector represents the zero-based index of that element in the source collection. This can be useful if the elements are in a known order and you want to do something with an element at a particular index, for example. It can also be useful if you want to retrieve the index of one or more elements. The second argument to selector represents the element to process.

This projection method requires the transform function, selector, to produce one value for each value in the source collection. If selector returns a value that is itself a collection, it is up to the consumer to traverse the subcollections manually. In such a situation, it might be better for your query to return a single coalesced collection of values. To achieve this, use the SelectMany method instead of Select. Although SelectMany works similarly to Select, it differs in that the transform function returns a collection that is then expanded by SelectMany before it is returned.

func SelectMany

func SelectMany[T, V any](selector func(T) Query[V]) func(q Query[T]) Query[V]

SelectMany projects each element of a collection to a Query, iterates and flattens the resulting collection into one collection.

func SelectManyBy

func SelectManyBy[T, V, O any](selector func(T) Query[V],
	resultSelector func(V, T) O) func(q Query[T]) Query[O]

SelectManyBy projects each element of a collection to a Query, iterates and flattens the resulting collection into one collection, and invokes a result selector function on each element therein.

func SelectManyByIndexed

func SelectManyByIndexed[T, V, O any](selector func(int, T) Query[V],
	resultSelector func(V, T) O) func(q Query[T]) Query[O]

func SelectManyIndexed

func SelectManyIndexed[T, V any](selector func(int, T) Query[V]) func(q Query[T]) Query[V]

SelectManyIndexed projects each element of a collection to a Query, iterates and flattens the resulting collection into one collection.

The first argument to selector represents the zero-based index of that element in the source collection. This can be useful if the elements are in a known order and you want to do something with an element at a particular index, for example. It can also be useful if you want to retrieve the index of one or more elements. The second argument to selector represents the element to process.

func Self added in v0.0.3

func Self[T any](t T) T

func SequenceEqual

func SequenceEqual[T comparable](q, q2 Query[T]) bool

SequenceEqual determines whether two collections are equal.

func Single

func Single[T any](q Query[T]) (r T, found bool)

Single returns the only element of a collection, and nil if there is not exactly one element in the collection.

func SingleWith

func SingleWith[T any](predicates ...func(T) bool) func(q Query[T]) (r T, found bool)

SingleWith returns the only element of a collection that satisfies a specified condition, and nil if more than one such element exists.

func SkipWhile

func SkipWhile[T any](predicates ...func(T) bool) func(q Query[T]) Query[T]

SkipWhile bypasses elements in a collection as long as a specified condition is true and then returns the remaining elements.

This method tests each element by using predicate and skips the element if the result is true. After the predicate function returns false for an element, that element and the remaining elements in source are returned and there are no more invocations of predicate.

func SkipWhileIndexed

func SkipWhileIndexed[T any](predicates ...func(int, T) bool) func(q Query[T]) Query[T]

SkipWhileIndexed bypasses elements in a collection as long as a specified condition is true and then returns the remaining elements. The element's index is used in the logic of the predicate function.

This method tests each element by using predicate and skips the element if the result is true. After the predicate function returns false for an element, that element and the remaining elements in source are returned and there are no more invocations of predicate.

func Sort

func Sort[T any](less func(i, j T) bool) func(q Query[T]) Query[T]

Sort returns a new query by sorting elements with provided less function in ascending order. The comparer function should return true if the parameter i is less than j. While this method is uglier than chaining OrderBy, OrderByDescending, ThenBy and ThenByDescending methods, it's performance is much better.

func Sum

func Sum[T constraints.Integer | constraints.Float](q Query[T]) (r T)

Sum computes the sum of a collection of numeric values.

Values can be of any integer type: int, int8, int16, int32, int64. The result is int64. Method returns zero if collection contains no elements.

func TakeWhile

func TakeWhile[T any](predicates ...func(T) bool) func(q Query[T]) Query[T]

TakeWhile returns elements from a collection as long as a specified condition is true, and then skips the remaining elements.

func TakeWhileIndexed

func TakeWhileIndexed[T any](predicates ...func(int, T) bool) func(q Query[T]) Query[T]

TakeWhileIndexed returns elements from a collection as long as a specified condition is true. The element's index is used in the logic of the predicate function. The first argument of predicate represents the zero-based index of the element within collection. The second argument represents the element to test.

func ThenBy

func ThenBy[T, V any](compare func(V, V) int, selector func(T) V) func(oq OrderedQuery[T]) OrderedQuery[T]

ThenBy performs a subsequent ordering of the elements in a collection in ascending order. This method enables you to specify multiple sort criteria by applying any number of ThenBy or ThenByDescending methods.

func ThenByDescending

func ThenByDescending[T, V any](compare func(V, V) int, selector func(T) V) func(oq OrderedQuery[T]) OrderedQuery[T]

ThenByDescending performs a subsequent ordering of the elements in a collection in descending order. This method enables you to specify multiple sort criteria by applying any number of ThenBy or ThenByDescending methods.

func ToChannel

func ToChannel[T any](q Query[T], result chan<- T)

ToChannel iterates over a collection and outputs each element to a channel, then closes it.

func ToMap

func ToMap[K comparable, V any](q Query[KeyValue[K, V]]) map[K]V

ToMap iterates over a collection and populates result map with elements. Collection elements have to be of KeyValue type to use this method. To populate a map with elements of different type use ToMapBy method. ToMap doesn't empty the result map before populating it.

func ToMapBy

func ToMapBy[K comparable, V, T any](keySelector func(T) K, valueSelector func(T) V) func(q Query[T]) map[K]V

ToMapBy iterates over a collection and populates the result map with elements. Functions keySelector and valueSelector are executed for each element of the collection to generate key and value for the map. Generated key and value types must be assignable to the map's key and value types. ToMapBy doesn't empty the result map before populating it.

func ToMapFromGroup added in v0.0.11

func ToMapFromGroup[K comparable, V any](q Query[Group[K, V]]) map[K][]V

func ToSlice

func ToSlice[T any](q Query[T]) []T

ToSlice iterates over a collection and saves the results in the slice pointed by v. It overwrites the existing slice, starting from index 0.

If the slice pointed by v has sufficient capacity, v will be pointed to a resliced slice. If it does not, a new underlying array will be allocated and v will point to it.

func ToString

func ToString(q Query[rune]) string

func ValidateQuery added in v0.0.3

func ValidateQuery[T comparable](q Query[T], output []T) bool

func Where

func Where[T any](predicates ...func(T) bool) func(q Query[T]) Query[T]

func WhereIndexed

func WhereIndexed[T any](predicates ...func(int, T) bool) func(q Query[T]) Query[T]

WhereIndexed filters a collection of values based on a predicate. Each element's index is used in the logic of the predicate function.

The first argument represents the zero-based index of the element within collection. The second argument of predicate represents the element to test.

func Zip

func Zip[T, V, O any](resultSelector func(T, V) O) func(q Query[T], q2 Query[V]) Query[O]

Zip applies a specified function to the corresponding elements of two collections, producing a collection of the results.

The method steps through the two input collections, applying function resultSelector to corresponding elements of the two collections. The method returns a collection of the values that are returned by resultSelector. If the input collections do not have the same number of elements, the method combines elements until it reaches the end of one of the collections. For example, if one collection has three elements and the other one has four, the result collection has only three elements.

Types

type Group

type Group[K, V any] struct {
	Key   K
	Group []V
}

Group is a type that is used to store the result of GroupBy method.

func (Group[K, V]) GetGroup added in v0.0.5

func (g Group[K, V]) GetGroup() []V

func (Group[K, V]) GetKey added in v0.0.5

func (g Group[K, V]) GetKey() K

type Iterator

type Iterator[T any] func() (item T, ok bool)

Iterator is an alias for function to iterate over data.

type KeyValue

type KeyValue[K comparable, V any] struct {
	Key   K
	Value V
}

KeyValue is a type that is used to iterate over a map (if query is created from a map). This type is also used by ToMap() method to output result of a query into a map.

type OrderedQuery

type OrderedQuery[T any] struct {
	Query[T]
	// contains filtered or unexported fields
}

OrderedQuery is the type returned from OrderBy, OrderByDescending ThenBy and ThenByDescending functions.

func DistinctOrderedQuery

func DistinctOrderedQuery[T comparable](oq OrderedQuery[T]) OrderedQuery[T]

DistinctOrderedQuery method returns distinct elements from a collection. The result is an ordered collection that contains no duplicate values.

NOTE: DistinctOrderedQuery method on OrderedQuery type has better performance than Distinct method on Query type.

type Query

type Query[T any] struct {
	Iterate func() Iterator[T]
}

Query is the type returned from query functions. It can be iterated manually as shown in the example.

func Append

func Append[T any](q Query[T], items ...T) Query[T]

Append inserts an item to the end of a collection, so it becomes the last item.

func Concat

func Concat[T any](q, q2 Query[T]) Query[T]

Concat concatenates two collections.

The Concat method differs from the Union method because the Concat method returns all the original elements in the input sequences. The Union method returns only unique elements.

func DefaultIfEmpty

func DefaultIfEmpty[T any](q Query[T], defaultValue T) Query[T]

DefaultIfEmpty returns the elements of the specified sequence if the sequence is empty.

func Distinct

func Distinct[T comparable](q Query[T]) Query[T]

Distinct method returns distinct elements from a collection. The result is an unordered collection that contains no duplicate values.

func Except

func Except[T comparable](q, q2 Query[T]) Query[T]

Except produces the set difference of two sequences. The set difference is the members of the first sequence that don't appear in the second sequence.

func FromChannel

func FromChannel[T any](source <-chan T) Query[T]

FromChannel initializes a linq query with passed channel, linq iterates over channel until it is closed.

func FromIterable

func FromIterable[T any](sourceFunc Iterator[T]) Query[T]

FromIterable initializes a linq query with custom collection passed. This collection has to implement Iterable interface, linq iterates over items, that has to implement Comparable interface or be basic types.

func FromMap

func FromMap[K comparable, V any](source map[K]V) Query[KeyValue[K, V]]

func FromSlice

func FromSlice[T any](source []T) Query[T]

func FromString

func FromString(source string) Query[rune]

FromString initializes a linq query with passed string, linq iterates over runes of string.

func Intersect

func Intersect[T comparable](q, q2 Query[T]) Query[T]

Intersect produces the set intersection of the source collection and the provided input collection. The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.

func Prepend

func Prepend[T any](q Query[T], items ...T) Query[T]

Prepend inserts an item to the beginning of a collection, so it becomes the first item.

func Range

func Range(start, count int) Query[int]

Range generates a sequence of integral numbers within a specified range.

func Repeat

func Repeat[T any](value T, count int) Query[T]

Repeat generates a sequence that contains one repeated value.

func Reverse

func Reverse[T any](q Query[T]) Query[T]

Reverse inverts the order of the elements in a collection.

Unlike OrderBy, this sorting method does not consider the actual values themselves in determining the order. Rather, it just returns the elements in the reverse order from which they are produced by the underlying source.

func Skip

func Skip[T any](q Query[T], count int) Query[T]

Skip bypasses a specified number of elements in a collection and then returns the remaining elements.

func Take

func Take[T any](q Query[T], count int) Query[T]

Take returns a specified number of contiguous elements from the start of a collection.

func Union

func Union[T comparable](q, q2 Query[T]) Query[T]

Union produces the set union of two collections.

This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input collection including duplicates.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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