Documentation
¶
Overview ¶
Package pipe provides utilities to pipe functions.
Index ¶
- type Builder
- type Pipe
- func Each[In, Out any](p *Pipe[iter.Seq[In]], f func(In) Out) *Pipe[iter.Seq[Out]]
- func Each2[KIn, VIn, KOut, VOut any](p *Pipe[iter.Seq2[KIn, VIn]], f func(KIn, VIn) (KOut, VOut)) *Pipe[iter.Seq2[KOut, VOut]]
- func From[In, Out any](p *Pipe[In], f func(In) Out) *Pipe[Out]
- func TryEach[In, Out any](p *Pipe[iter.Seq[In]], f func(In) (Out, error)) *Pipe[iter.Seq2[Out, error]]
- func TryFrom[In, Out any](p *Pipe[In], f func(In) (Out, error)) *Pipe[Out]
- func Value[T any](v T) *Pipe[T]
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Pipe ¶
type Pipe[T any] struct { // contains filtered or unexported fields }
Pipe represents the term of the pipeline.
func From ¶
From is like Pipe.Chain except f returns different type.
func TryFrom ¶
TryFrom is like Pipe.TryChain except f returns different type.
func Value ¶
Value returns a term.
Example ¶
package main
import (
"fmt"
"iter"
"strings"
"github.com/lufia/pipe"
)
func tee[T any](v T) T {
fmt.Println(v)
return v
}
func require[T ~string](v T) (T, error) {
if len(v) == 0 {
return "", fmt.Errorf("zero length")
}
return v, nil
}
// After Go 1.23 is released, slices.Values will replace this.
func values[T any](a []T) iter.Seq[T] {
return func(yield func(T) bool) {
for _, s := range a {
if !yield(s) {
break
}
}
}
}
// After Go 1.23 is released, slices.Collect will replace this.
func collect[T any](seq iter.Seq[T]) []T {
var a []T
for v := range seq {
a = append(a, v)
}
return a
}
func main() {
p1 := pipe.Value("hello world").
TryChain(require).
Chain(tee).
Chain(strings.ToUpper)
p2 := pipe.From(p1, strings.Fields)
p3 := pipe.From(p2, values)
p4 := pipe.Each(p3, func(s string) string {
return s + "!"
})
p5 := pipe.From(p4, collect)
a, _ := p5.Eval()
fmt.Println(a)
}
Output: hello world [HELLO! WORLD!]
Example (Url) ¶
package main
import (
"fmt"
"net/url"
"github.com/lufia/pipe"
)
func WithPath(s string) func(u *url.URL) *url.URL {
return func(u *url.URL) *url.URL {
u.Path = s
return u
}
}
func WithParam(k, v string) func(u *url.URL) *url.URL {
return func(u *url.URL) *url.URL {
q := u.Query()
q.Set(k, v)
u.RawQuery = q.Encode()
return u
}
}
func main() {
u, _ := pipe.TryFrom(pipe.Value("https://example.com"), url.Parse).
Chain(WithPath("/query")).
Chain(WithParam("key", "value")).
Eval()
fmt.Println(u.String())
}
Output: https://example.com/query?key=value
Click to show internal directories.
Click to hide internal directories.