mapcarとfilter

高階関数の練習に、mapcarfilter を作ってみた。

まずは mapcar から。

package main

import "fmt"

func mapcar(f func(int) int, a []int) []int {
    b := make([]int, 0)
    for _, x := range a {
        b = append(b, f(x))
    }
    return b
}

func square(x int) int {
    return x * x
}

func main() {
    a := []int{ 1,2,3,4,5 }
    fmt.Println(a)

    b := mapcar(square, a)
    fmt.Println(b)

    cube := func(x int) int { return x * x * x }
    c := mapcar(cube, a)
    fmt.Println(c)
}
^o^ > go run mapcar.go
[1 2 3 4 5]
[1 4 9 16 25]
[1 8 27 64 125]

つぎは filter

package main

import "fmt"

func filter(f func(int) bool, a []int) []int {
    b := make([]int, 0)
    for _, x := range a {
        if f(x) {
            b = append(b, x)
        }
    }
    return b
}

func even(i int) bool {
    return i % 2 == 0
}

func main() {
    a := []int{ 1,2,3,4,5,6,7,8,9 }
    b := filter(even, a)
    fmt.Println(b)
}
^o^ > go run filter.go
[2 4 6 8]