GO generics - function implementation

103 views
Skip to first unread message

Stanimir Stankov

unread,
Feb 9, 2023, 2:26:10 PM2/9/23
to golang-nuts
Need help!
a function that allows you to group the elements of a slice based on a passed function that returns a key for each element of the slice

func Partition[S any, K comparable](slice []S, fn func(S) K) map[K][]S { }


a function that allows you to select elements from a slice
based on a given predicate function

func Select[S any](slice []S, fn func(S) bool) []S {}

Axel Wagner

unread,
Feb 9, 2023, 3:25:59 PM2/9/23
to Stanimir Stankov, golang-nuts
These look like homework assignments. You should be aware that if that's the case, you are essentially throwing away the money you are spending on your education by refusing to learn what it's trying to teach - that is, you are paying for a product that you don't want.

That being said (who am I to judge), the solutions are very straight forward:

func Partition[S any, K comparable](slice []S, fn func(S) K) map[K][]S {
    m := make(map[K][]S)
    for _, e := range slice {
        k := fn(e)
        m[k] = append(m[k], e)
    }
    return m
}

func Select[S any](slice []S, fn func(S) bool) []S {
    var out []S
    for _, e := range slice {
        if fn(e) {
            out = append(out, e)
        }
    }
    return out
}

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/61fffde8-d9cb-43c8-822e-557d3a5b4a0dn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages