Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions seq/seq.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,3 +195,28 @@ func FlatMap[T any, R any](s iter.Seq[T], f func(T) iter.Seq[R]) iter.Seq[R] {
}
}
}

// Pairwise returns an iterator over consecutive pairs of elements.
// For example, [a, b, c, d] yields [(a, b), (b, c), (c, d)].
func Pairwise[T any](s iter.Seq[T]) iter.Seq2[T, T] {
return func(yield func(T, T) bool) {
next, stop := iter.Pull(s)
defer stop()

prev, ok := next()
if !ok {
return
}

for {
current, ok := next()
if !ok {
return
}
if !yield(prev, current) {
return
}
prev = current
}
}
}
44 changes: 44 additions & 0 deletions seq/seq_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,50 @@ func TestFlatMap(t *testing.T) {
}
}

func TestPairwise(t *testing.T) {
testCases := []struct {
name string
input []string
want []pair[string, string]
}{
{
name: "empty",
input: []string{},
want: []pair[string, string]{},
},
{
name: "only one element",
input: []string{"a"},
want: []pair[string, string]{},
},
{
name: "ok",
input: []string{"a", "b", "c", "d"},
want: []pair[string, string]{
{"a", "b"},
{"b", "c"},
{"c", "d"},
},
},
{
name: "3 elements",
input: []string{"a", "b", "c"},
want: []pair[string, string]{
{"a", "b"},
{"b", "c"},
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
got := pairs(seq.Pairwise(slices.Values(tc.input)))
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("result mismatch:\n\twant: %#v\n\t got: %#v", tc.want, got)
}
})
}
}

func list[T any](xs ...T) iter.Seq[T] {
return func(yield func(T) bool) {
for _, x := range xs {
Expand Down
Loading