2

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?

ThePiercingPrince
  • 1,873
  • 13
  • 21

1 Answers1

6

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{}.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • 1
    How does one "re-add" the type information when using Map then? (It seems like this would be the equivalent of using `Object` in C#/Java..?) – user2864740 Dec 31 '13 at 02:52
  • @user2864740: If you have a variable of `interface{}` type and want to get it back into some more concrete type, you can use type assertions. For example, if you know the value is an int, `someVariable.(int)` will get the int back out of the `interface{}` variable. – Chuck Dec 31 '13 at 18:12