Home >Backend Development >Golang >How Can We Effectively Emulate Haskell's `fmap` in Go?

How Can We Effectively Emulate Haskell's `fmap` in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 18:48:14825browse

How Can We Effectively Emulate Haskell's `fmap` in Go?

Emulating fmap in Go: A Practical Approach

In Go, emulating the expressive power of Haskell's typeclasses presents challenges. One such example is the emulation of fmap, a fundamental operation in functional programming.

The Challenge

Consider the following attempt to implement fmap in Go:

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 implementation fails because Go methods cannot introduce new type parameters. As a result, the fmap method cannot access the B type.

A Practical Solution

While using generics and methods to emulate typeclasses in Go has limitations, it is possible 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)}
}

This approach provides the desired functionality without the constraints of Go's type system. However, it is crucial to evaluate whether such emulation aligns with the idiomatic approach in Go.

The above is the detailed content of How Can We Effectively Emulate Haskell's `fmap` in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn