kdungs / go-result

Result types for Go; because (T, error) can be considered a ✨ monad ✨.
MIT License
1 stars 0 forks source link

"Consuming" functions #8

Closed kdungs closed 1 year ago

kdungs commented 1 year ago

Could probably also be used for "defer close".

kdungs commented 1 year ago

Calling them Consume is probably not a good idea since that kind of implies it could only be done once. Instead, Do might be a better name.

Since the signature(s) doesn't require type parameter, this could even be done as (a) member function(s). For symmetry, it'll probably best to at least have free versions, as well.

I.e.

func Do(R[T], func(T)) error
func DoE(R[T], func(T) error) error

Kind of corresponds to fmap / bind without a result value... We might also want to do the same for Zip...

Then we could do stuff like

f := result.Wrap(os.Open("foo"))
defer result.DoE(f, func(f *os.File) error { f.Close() })

or use it to consume results at the end of a computation like in example_test.go:

out := result.ZipE(of, cnt, writeCountsSorted)
if _, err := out.Unwrap(); err != nil {
    log.Fatalf("%v", err)
}
fmt.Printf("%s", buf.String())

vs.

if err := result.ZipConsume(of, cnt, writeCountsSorted_); err != nil {
    log.Fatalf("%v", err)
}
kdungs commented 1 year ago

Calling them Consume is probably not a good idea since that kind of implies it could only be done once. Instead, Do might be a better name.

The functions do however produce a return value that is no longer an R[T] so in that sense, they get consumed...

kdungs commented 1 year ago

For now, the free versions should be enough.