filter two lambda arrays in go

In Go, you can use anonymous functions, also known as lambda functions, to filter arrays. Here's an example of how to filter two lambda arrays in Go:

main.go
package main

import (
    "fmt"
)

func main() {
    // Define the two arrays
    numbers1 := []int{1, 2, 3, 4, 5}
    numbers2 := []int{6, 7, 8, 9, 10}

    // Filter the arrays using anonymous functions
    filteredNumbers1 := filter(numbers1, func(n int) bool {
        return n%2 == 0
    })

    filteredNumbers2 := filter(numbers2, func(n int) bool {
        return n%3 == 0
    })

    // Print the filtered arrays
    fmt.Println(filteredNumbers1) // [2 4]
    fmt.Println(filteredNumbers2) // [6 9]
}

// The filter function takes an array and a lambda function and returns a new array
// with only the elements that passed the test in the lambda function
func filter(numbers []int, fn func(int) bool) []int {
    result := []int{}

    for _, n := range numbers {
        if fn(n) {
            result = append(result, n)
        }
    }

    return result
}
870 chars
39 lines

In the example above, we define two arrays numbers1 and numbers2 and filter them using anonymous functions that test if a number is even (for numbers1) or divisible by 3 (for numbers2). We use the filter function to do the actual filtering, which takes an array and a lambda function and returns a new array with only the elements that passed the test in the lambda function. The filter function is defined using a func keyword, which is a way to define a named function in Go.

gistlibby LogSnag