Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Helpers for combine function and tuple #462

Open
0x587 opened this issue Jun 6, 2024 · 3 comments
Open

Proposal: Helpers for combine function and tuple #462

0x587 opened this issue Jun 6, 2024 · 3 comments

Comments

@0x587
Copy link

0x587 commented Jun 6, 2024

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 0x587 changed the title Helpers for combine function and tuple Proposal: Helpers for combine function and tuple Jun 6, 2024
@0x587
Copy link
Author

0x587 commented Jun 6, 2024

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

@samber
Copy link
Owner

samber commented Jul 26, 2024

I suppose a Map2...MapX(a A, b B, ...x X) R would do the job.

If I understand your needs, returning a tuple2 is like returning a single value.

@0x587
Copy link
Author

0x587 commented Jul 26, 2024

oh yes your solution is possible.
In most cases, our function will return (val, err). When an error occurs, we want to stop or ignore the process. If only have Map2 is difficult to apply to this situation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants