英文:
Type variables in Go
问题
在Haskell中,map
的类型是:
map :: (a -> b) -> [a] -> [b]
请注意,a
和b
不是具体的类型,而是类型变量,这意味着它们可以是任何类型,只要在特定的函数调用中每个变量始终引用相同的类型。在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
所以,它接受的不是一个从a
到b
的函数,而是一个从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{}
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论