Home >Backend Development >Golang >How Can Haskell's `fmap` Be Effectively Emulated in Go Using Generics?
Emulating Haskell's fmap in Go
The inability to have method arguments use parameterized types presents a challenge when emulating Haskell typeclasses in Go. Consider the following example attempting to emulate fmap:
type S[A any] struct { contents A } type Functor [A any, B any] interface{ fmap(f func(A)B) B } func (x S[A]) fmap (f func(A)B) S[B] { x.contents = f(x.contents) return x }
This code fails due to the undefined type B in the interface implementation.
Workaround Using a Top-Level Function
Since Go methods cannot introduce new type parameters, one workaround is to implement fmap as a top-level function:
func Fmap[A, B any](sa S[A], f func(A) B) S[B] { return S[B]{contents: f(sa.contents)} }
Alternative Approaches
While this workaround solves the immediate issue, it highlights that emulating Haskell typeclasses using generics and methods is not a straightforward endeavor in Go. Alternative approaches could involve:
The above is the detailed content of How Can Haskell's `fmap` Be Effectively Emulated in Go Using Generics?. For more information, please follow other related articles on the PHP Chinese website!