Created
April 3, 2022 16:44
-
-
Save fogfish/6df9d9e0b09c88efed27f05c0c84cf18 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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