samber / lo

💥 A Lodash-style Go library based on Go 1.18+ Generics (map, filter, contains, find...)
https://pkg.go.dev/github.com/samber/lo
MIT License
16.18k stars 735 forks source link

Proposal: Helpers for combine function and tuple #462

Open 0x587 opened 1 month ago

0x587 commented 1 month ago

Perhaps we could add some helpers that combine functions and Tuples, so that multi-parameter functions (both input and output) can be easily applied to Maps.

Like This

package main

import "github.com/samber/lo"

func f21(a, b int) int {
    return a + b
}

func f22(a, b int) (int, int) {
    return a, b
}

func TupleFun21[A any, B any, R any](f func(A, B) R) func(lo.Tuple2[A, B]) R {
    return func(tuple lo.Tuple2[A, B]) R {
        a := f(tuple.A, tuple.B)
        return a
    }
}

func TupleFun22[A any, B any, R1 any, R2 any](f func(A, B) (R1, R2)) func(lo.Tuple2[A, B]) lo.Tuple2[R1, R2] {
    return func(tuple lo.Tuple2[A, B]) lo.Tuple2[R1, R2] {
        a, b := f(tuple.A, tuple.B)
        return lo.Tuple2[R1, R2]{A: a, B: b}
    }
}

func FakeIndex[A any, R any](f func(A) R) func(A, int) R {
    return func(a A, _ int) R {
        return f(a)
    }
}

func main() {
    data := []lo.Tuple2[int, int]{
        {1, 2},
        {3, 4},
        {5, 6},
    }
    lo.Map(data, FakeIndex(TupleFun21(f21)))
    lo.Map(data, FakeIndex(TupleFun22(f22)))
}
0x587 commented 1 month ago

I think if this feature is implemented, we can write fewer anonymous functions just for repeated parameter conversion.