First class functions in Go

前端 未结 5 1510
鱼传尺愫
鱼传尺愫 2021-01-30 08:49

I come from JavaScript which has first class function support. For example you can:

  • pass a function as a parameter to another function
  • return a function f
5条回答
  •  广开言路
    2021-01-30 09:11

    package main
    
    import (
        "fmt"
    )
    
    type Lx func(int) int
    
    func cmb(f, g Lx) Lx {
        return func(x int) int {
            return g(f(x))
        }
    }
    
    func inc(x int) int {
        return x + 1
    }
    
    func sum(x int) int {
        result := 0
    
        for i := 0; i < x; i++ {
            result += i
        }
    
        return result
    }
    
    func main() {
        n := 666
    
        fmt.Println(cmb(inc, sum)(n))
        fmt.Println(n * (n + 1) / 2)
    }
    

    output:

    222111
    222111
    

提交回复
热议问题