These are chat archives for ramda/ramda

23rd
Apr 2016
Brad Compton (he/him)
@Bradcomp
Apr 23 2016 04:29

Can I ask a general question here about functional / monadic patterns? I'm learning to use Futures for async control, and I've set up my database layer so it returns Futures. In the case of a findOne, the signature is Query -> Future Maybe Document. I'd like to perform another async call using the data from the document.

I'd like to use chain to avoid having to call fork twice, but the Maybe get's in the way of being able to do that, and I'm not sure how to avoid it without using something like S.maybe, which feels like cheating. I know there are functions like sequence that can help with traversables, but is there a general pattern that can help avoid these deeply nested structures?

Aldwin Vlasblom
@Avaq
Apr 23 2016 06:26

@Bradcomp It depends on your use-case, but for most of mine I like to do this:

const maybeToFuture = curry((x, m) => S.maybe(Future.reject(x), Future.of, m));

findOne(123) //> Future[a, Maybe Document]
.chain(maybeToFuture(httpError(404, 'Document not found'))) //> Future[NotFoundError, Document]
.chain(doc => /*...*/)

Alternatively, you might want to keep the Maybe (if you wish to handle its error differently from the Future at the edge of your program), at which point you may want to look into using a Maybe.T(Future) structure or using sequence to turn Future Maybe Future into Future Future Maybe which can be flattened to Future Maybe.

Brad Compton (he/him)
@Bradcomp
Apr 23 2016 15:17

@Avaq Thanks for the advice! I didn't know you could use sequence on Maybe, but I just looked at Sanctuary's docs and saw that that it works. The maybeToFuture is a good idea, and in my current case that's probably what I'll do.

On a side note, your flutures are much appreciated!

Aldwin Vlasblom
@Avaq
Apr 23 2016 15:21
Great to hear! :D