1
votes

I am trying to create a function, takes in a predicate, and a list and calls the predicate on each item. I tried something like this

func hello(list []int, f func( int ) ) {
    for _, curr := range list {
        f(curr)
    }
}

The problem is, that my predicate may have other parameters that need to be passed in first, something like func pred(a string, b string, curr int, c string). So now I cant just call hello without first creating a wrapper function which returns a function that only requires the int part (named curr). Is there a clean solution to this? I almost want to pass in a struct, where each key is a parameter name, and each value, the value to pass in as that parameter. But then I somehow need to leave the "int part" empty, and know to use it during the evalutation of hello. I'm not too familiar with interfaces, but maybe I can leverage them somehow? Not too sure what the best practices are for solving a problem of this type.

1
Can you give an example of a function where you might call this? Where would the a, b, and c parameters come from? - David Maze
I think "creating a wrapper function which returns a function that only requires the int part" is the right way to do it. Have you tried it? How was it not "clean"? - Chris Drew
a,b,c would be known values at the time when I want to use the predicate - user13484252
if a, b, and c are known at the point you use the predicate, then you can still use a single-arg predicate: hello(list,func(curr int) { use a,b,c here }) - Burak Serdar
What seems like a lot of overhead? Closures are used for “passing” data to function calls all the time, and are usually called once in that case. - JimB

1 Answers

1
votes

Use Function literals to solve this problem. The scenario in the question is an important use case for the feature:

hello([]int{1, 2, 3, 4}, func(cur int) { pred(a, b, cur, c) })

If a, b and c are in scope, there's no need for a function that returns a function as claimed in the question.

See it in action on the playground