Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"fmt"
"strings"
)
//
//
type HKT[F, A any] interface {
HKT1(F)
HKT2(A)
}
type Functor[F, A, B any] interface {
Map(func(A) B, HKT[F, A]) HKT[F, B]
}
//
//
type MaybeType any
type MaybeKind[A any] HKT[MaybeType, A]
//
//
type Some[A any] struct{ Value A }
func (Some[A]) HKT1(MaybeType) {}
func (Some[A]) HKT2(A) {}
//
//
type None[A any] int
func (None[A]) HKT1(MaybeType) {}
func (None[A]) HKT2(A) {}
//
//
func fmap[A, B any](f func(A) B, fa MaybeKind[A]) MaybeKind[B] {
switch x := fa.(type) {
case Some[A]:
return Some[B]{Value: f(x.Value)}
default:
return None[B](0)
}
}
//
//
type Maybe[A, B any] func(func(A) B, MaybeKind[A]) MaybeKind[B]
func (eff Maybe[A, B]) Map(f func(A) B, fa HKT[MaybeType, A]) HKT[MaybeType, B] {
return eff(f, fa)
}
var maybe Functor[MaybeType, int, string] = Maybe[int, string](
fmap[int, string],
)
//
//
func main() {
double := func(x int) string { return strings.Repeat("x", x) }
fmt.Println(
maybe.Map(double, Some[int]{5}),
)
fmt.Println(
maybe.Map(double, None[int](0)),
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment