1 Star 0 Fork 0

Erdian718/linq

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
linq.go 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
Erdian718 提交于 2025-02-20 13:06 +08:00 . Change APIs for Map and Zip
// Package linq provides extra features for go's standard iter library.
package linq
import (
"cmp"
"errors"
"iter"
)
// Errors.
var (
ErrNotFound = errors.New("linq: element is not found")
ErrNotSingle = errors.New("linq: sequence is not single")
)
// Entry represents an entry of map.
type Entry[K comparable, V any] struct {
Key K // The map key.
Value V // The map value.
}
// Max returns the maximal element in s.
func Max[E cmp.Ordered](s Seq[E]) (E, error) {
return s.Max(cmp.Compare)
}
// Min returns the minimal element in s.
func Min[E cmp.Ordered](s Seq[E]) (E, error) {
return s.Min(cmp.Compare)
}
// Equal reports whether two sequences are equal.
func Equal[E comparable](s1, s2 Seq[E]) (bool, error) {
return s1.Equal(s2, func(e1, e2 E) bool { return e1 == e2 })
}
// Sort sorts a sequence of any ordered type in ascending order.
func Sort[E cmp.Ordered](s Seq[E]) Seq[E] {
return s.Sort(cmp.Compare)
}
// Map maps sequence using function f.
func Map[E, R any](s Seq[E], f func(E) (R, error)) Seq[R] {
return func(yield func(R, error) bool) {
for e, err := range s {
if err != nil {
var r R
yield(r, err)
return
}
if !yield(f(e)) {
return
}
}
}
}
// Zip applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
func Zip[X, Y, R any](xs Seq[X], ys Seq[Y], f func(X, Y) (R, error)) Seq[R] {
return func(yield func(R, error) bool) {
next, stop := iter.Pull2(iter.Seq2[Y, error](ys))
defer stop()
var zero R
for x, err := range xs {
if err != nil {
yield(zero, err)
return
}
y, err, ok := next()
if !ok {
return
}
if err != nil {
yield(zero, err)
return
}
if !yield(f(x, y)) {
return
}
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/erdian718/linq.git
git@gitee.com:erdian718/linq.git
erdian718
linq
linq
main

搜索帮助