Home > Backend Development > Golang > How Can Haskell's `fmap` Be Effectively Emulated in Go Using Generics?

How Can Haskell's `fmap` Be Effectively Emulated in Go Using Generics?

Mary-Kate Olsen
Release: 2024-12-19 16:52:13
Original
333 people have browsed it

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
}
Copy after login

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)}
}
Copy after login

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:

  • Using inheritance: Design an inheritance hierarchy where each type implements a method for a specific function.
  • Using interfaces with explicit method implementations: Define interfaces with explicitly implemented methods that accept generic types as arguments.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template