samber / mo

🦄 Monads and popular FP abstractions, powered by Go 1.18+ Generics (Option, Result, Either...)
https://pkg.go.dev/github.com/samber/mo
MIT License
2.47k stars 80 forks source link

Auto-Boxing in method FlatMap #2

Closed orbitoo closed 2 years ago

orbitoo commented 2 years ago
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]()
}
rbee3u commented 2 years ago

That is what o.Map do

samber commented 2 years ago

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!