Type variables in Go

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

Type variables in Go

问题

在Haskell中,map的类型是:

map :: (a -> b) -> [a] -> [b]

请注意,ab不是具体的类型,而是类型变量,这意味着它们可以是任何类型,只要在特定的函数调用中每个变量始终引用相同的类型。在Go语言中如何实现相同的功能呢?

英文:

In Haskell, map has type:

map :: (a -> b) -> [a] -> [b]

Note that a and b are not absolute types but type variables, which mean that they can be any type as long as each variable always refer to the same type in a specific function call. How to do the same thing in Go?

答案1

得分: 6

Go语言没有像Haskell那样的Hindley-Milner类型系统,所以它不能完全表达相同的东西,比如带有变量的类型。在Go中,实现类型不可知的函数是通过接口来实现的。如果你想表示"任意类型",通常会写成一个空接口(interface{})。标准库中Map函数的类型是:

func Map(iter Iterable, f func(interface{}) interface{}) Iterable

所以,它接受的不是一个从ab的函数,而是一个从interface{}interface{}的函数。

英文:

Go does not have a Hindley-Milner type system like Haskell's, so it can't express exactly the same things, like types with variables. The way type-agnostic functions are done in Go is with interfaces. If you want to express "any type", that's usually written as an empty interface (interface{}). The type of the Map function in the standard library is:

func Map(iter Iterable, f func(interface{}) interface{}) Iterable

So instead of taking a function that goes from a to b, it takes a function that goes from interface{} to interface{}.

huangapple
  • 本文由 发表于 2013年12月31日 10:29:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/20850831.html
匿名

发表评论

匿名网友

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

确定