samber / mo

🦄 Monads and popular FP abstractions, powered by Go 1.18+ Generics (Option, Result, Either...)

Home Page:https://pkg.go.dev/github.com/samber/mo

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Auto-Boxing in method FlatMap

orbitoo opened this issue · comments

package main

import "github.com/samber/mo"

func main() {
	var x float64 = 2.0
	op := mo.Some(x)
	square := func(x float64) mo.Option[float64] { return mo.Some(x * x) }
	cubic := func(x float64) mo.Option[float64] { return mo.Some(x * x * x) }
	print(op.FlatMap(square).FlatMap(cubic).OrElse(-1))
}

This is an example of using this package,
but I suppose function square should be

	square := func(x float64) float64 { return x * x }

This declaration of mapping functions is better, I think.

Consider change the FlatMap into

func (o Option[T]) FlatMap(mapper func(T) T) Option[T] {
	if o.isPresent {
		return Some(mapper(o.value))
	}
	return None[T]()
}

That is what o.Map do

FlatMap can return a None value.

Map always returns a Some value.

I don't see any error here 🤔.

I'm closing. Feel free to open it again for more questions!