Go语言有lambda表达式或类似的东西吗?

huangapple go评论105阅读模式
英文:

Does Go have lambda expressions or anything similar?

问题

Go支持lambda表达式或类似的东西吗?我想将一个使用lambda表达式(Ruby)的库移植到Go语言。

英文:

Does Go support lambda expressions or anything similar?

I want to port a library from another language that uses lambda expressions (Ruby).

答案1

得分: 95

是的。

这是一个例子,仔细复制和粘贴:

> package main
>
> import fmt "fmt"
>
> type Stringy func() string
>
> func foo() string{
> return "Stringy function"
> }
>
> func takesAFunction(foo Stringy){
> fmt.Printf("takesAFunction: %v\n", foo())
> }
>
> func returnsAFunction()Stringy{
> return func()string{
> fmt.Printf("Inner stringy function\n");
> return "bar" // have to return a string to be stringy
> }
> }
>
> func main(){
> takesAFunction(foo);
> var f Stringy = returnsAFunction();
> f();
> var baz Stringy = func()string{
> return "anonymous stringy\n"
> };
> fmt.Printf(baz());
> }

英文:

Yes.

Here is an example, copied and pasted carefully:

> package main
>
> import fmt "fmt"
>
> type Stringy func() string
>
> func foo() string{
> return "Stringy function"
> }
>
> func takesAFunction(foo Stringy){
> fmt.Printf("takesAFunction: %v\n", foo())
> }
>
> func returnsAFunction()Stringy{
> return func()string{
> fmt.Printf("Inner stringy function\n");
> return "bar" // have to return a string to be stringy
> }
> }
>
> func main(){
> takesAFunction(foo);
> var f Stringy = returnsAFunction();
> f();
> var baz Stringy = func()string{
> return "anonymous stringy\n"
> };
> fmt.Printf(baz());
> }

答案2

得分: 57

Lambda表达式也被称为函数字面量。Go完全支持它们。

请参阅语言规范:
http://golang.org/ref/spec#Function_literals

请参阅代码演示,其中包含示例和描述:
http://golang.org/doc/codewalk/functions/

英文:

Lambda expressions are also called function literals. Go supports them completely.

See the language spec:
http://golang.org/ref/spec#Function_literals

See a code-walk, with examples and a description:
http://golang.org/doc/codewalk/functions/

答案3

得分: 20

在计算机编程中,匿名函数或lambda抽象(函数字面量)是一个没有绑定到标识符的函数定义,而Go支持匿名函数,可以形成闭包。当你想要内联定义一个函数而不必给它命名时,匿名函数非常有用。

package main
import "fmt"

func intSeq() func() int {
    i := 0
    return func() int {
        i += 1
        return i
    }
}

func main() {
   nextInt := intSeq()
   fmt.Println(nextInt())
   fmt.Println(nextInt())
   fmt.Println(nextInt())
   newInts := intSeq()
   fmt.Println(newInts())
}

函数intSeq返回另一个函数,我们在intSeq的主体中匿名定义它。返回的函数通过闭包封闭了变量i

输出结果:

1
2
3
1
英文:

> Yes

In computer programming, an anonymous function or lambda abstraction (function literal) is a function definition that is not bound to an identifier, and Go supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

    package main
    import "fmt"
    
    func intSeq() func() int {
        i := 0
        return func() int {
            i += 1
            return i
        }
    }

    
    func main() {
       nextInt := intSeq()
       fmt.Println(nextInt())
       fmt.Println(nextInt())
       fmt.Println(nextInt())
       newInts := intSeq()
       fmt.Println(newInts())
    }

function intSeq returns another function, which we define anonymously in the body of intSeq. The returned function closes over the variable i to form a closure.

Output
$ go run closures.go
1
2
3
1

答案4

得分: 12

golang中似乎没有lambda表达式,但是可以使用字面量匿名函数,我在学习时写了一些例子来比较与JS中的等效情况!

无参数返回字符串:

func() string {
    return "some String Value"
}
//Js类似:() => 'some String Value'

带有字符串参数和返回字符串:

func(arg string) string {
    return "some String" + arg
}
//Js类似:(arg) => "some String Value" + arg

无参数和无返回值(void):

func() {
   fmt.Println("Some String Value")
} 
//Js类似:() => {console.log("Some String Value")}

带有参数和无返回值(void):

func(arg string) {
    fmt.Println("Some String " + arg)
}
//Js类似:(arg) => {console.log("Some String Value" + arg)}
英文:

The golang does not seem to make lambda expressions, but you can use a literal anonymous function, I wrote some examples when I was studying comparing the equivalent in JS!

no args return string:

func() string {
    return "some String Value"
}
//Js similar: () => 'some String Value'

with string args and return string

func(arg string) string {
    return "some String" + arg
}
//Js similar: (arg) => "some String Value" + arg

no arguments and no returns (void)

func() {
   fmt.Println("Some String Value")
} 
//Js similar: () => {console.log("Some String Value")}

with Arguments and no returns (void)

func(arg string) {
    fmt.Println("Some String " + arg)
}
//Js: (arg) => {console.log("Some String Value" + arg)}

答案5

得分: 3

一个还没有提供的例子是直接将值赋给变量/从匿名函数中赋值,例如

test1, test2 := func() (string, string) {
    x := []string{"hello", "world"}
    return x[0], x[1]
}()

注意:你需要在函数的末尾加上括号()来执行它并返回值,否则只会返回函数本身,并产生assignment mismatch: 2 variable but 1 values错误。

英文:

An example that hasn't been provided yet that I was looking for is to assign values directly to variable/s from an anonymous function e.g.

test1, test2 := func() (string, string) {
	x := []string{"hello", "world"}
	return x[0], x[1]
}()

Note: you require brackets () at the end of the function to execute it and return the values otherwise only the function is returned and produces an assignment mismatch: 2 variable but 1 values error.

答案6

得分: 2

这是一个“柯里化函数”的例子。然而,相对于其他语言(如Swift、C#等)中的lambda函数语法,该语法似乎不太清晰。

func main() int { 
  var f func(string) func(string) int
  f = func(_x1 string) func(string) int { return func(_x2 string) int { return strings.Compare(_x1,_x2) } }
  return ((f)("b"))("a")
}
英文:

Here is a 'curried function' example. However the syntax seems unclear, relative to the lambda function syntax in other languages such as Swift, C#, etc.

func main() int { 
  var f func(string) func(string) int
  f = func(_x1 string) func(string) int { return func(_x2 string) int { return strings.Compare(_x1,_x2) } }
  return ((f)("b"))("a")
}

答案7

得分: 0

是的,因为它是一种完全功能的语言,但没有胖箭头(=>)或细箭头(->)作为通常的lambda符号,并且为了清晰和简单起见,使用func关键字。

英文:

Yes, since it is a fully functional language, but has no fat arrow (=>) or thin arrow (->) as the usual lambda sign, and uses the func keyword for the sake of clarity and simplicity.

huangapple
  • 本文由 发表于 2012年8月2日 03:37:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/11766320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定