kcmallard
kcmallard

Reputation: 197

Does Go allow a function to use another function as a parameter?

The problem is happening at line 17 in the Go code. Below is the program in python and Go so you can see exactly what I'm attempting to do. Python works, my Go attempts have all failed. Already read golang.org back to back, and google turned up nothing, as well.

def my_filter(x):
  if x % 5 == 0:
    return True
  return False

#Function which returns a list of those numbers which satisfy the filter
def my_finc(Z, my_filter):

  a = []
  for x in Z:
    if my_filter(x) == True:
      a.append(x)
  return a

print(my_finc([10, 4, 5, 17, 25, 57, 335], my_filter))

Now, the Go version which I'm having troubles with:

package main

import "fmt"

func Filter(a []int) bool {
    var z bool
    for i := 0; i < len(a); i++ {
        if a[i]%5 == 0 {
            z = true
        } else {
            z = false
        }
    }
    return z
}

func finc(b []int, Filter) []int {
    var c []int
    for i := 0; i < len(c); i++ {
        if Filter(b) == true {
            c = append(c, b[i])
        }
    }
    return c
}

func main() {
    fmt.Println(finc([]int{1, 10, 2, 5, 36, 25, 123}, Filter))
}

Upvotes: 4

Views: 149

Answers (1)

Logiraptor
Logiraptor

Reputation: 1528

Yes, Go can have functions as parameters:

package main

import "fmt"

func myFilter(a int) bool {
    return a%5 == 0
}

type Filter func(int) bool

func finc(b []int, filter Filter) []int {
    var c []int
    for _, i := range b {
        if filter(i) {
            c = append(c, i)
        }
    }
    return c
}

func main() {
    fmt.Println(finc([]int{1, 10, 2, 5, 36, 25, 123}, myFilter))
}

The key is you need a type to pass in.

type Filter func(int) bool

I also cleaned up a bit of the code to make it more idiomatic. I replaced your for loops with range clauses.

for i := 0; i < len(b); i++ {
    if filter(b[i]) == true {
        c = append(c, b[i])
    }
}

becomes

for _, i := range b {
    if filter(i) {
        c = append(c, i)
    }
}

Upvotes: 8

Related Questions