gcanti / fp-ts

Functional programming in TypeScript
https://gcanti.github.io/fp-ts/
MIT License
10.76k stars 503 forks source link

Better workflow for working with monad transformers #1145

Closed prescientmoon closed 4 years ago

prescientmoon commented 4 years ago

🚀 Feature request

Current Behavior

So say i combine WriterT with StateT ReaderT and Either for a (I'd say pretty common) monad stack. Everything is great when it comes to typing, and I can even get a barebones monad instance, but no more than that. What if I need a curried map / chain function? What if I want to instantiate the monad with a right value? Since the of operation gives me a left I have to make my own helper.

Desired Behavior

I'd like to have a way to just call a function and get a bunch of curried functions and helpers I can use with the stack I chose

Suggested Solution

We can already get a barebones monad so maybe we need a function which takes that and returns curried helpers

Who does this impact? Who is this for?

People who use monad transformers

Describe alternatives you've considered

Writing the helpers myself for each new stack, gets boring and repetitive

Additional context

I'm sorry if this library already offers something to solve this, in my limited time I wasn't able to find any solution

Your environment

Software Version(s)
fp-ts 2.5.1
TypeScript 3.7
aqrln commented 4 years ago

You can get curried pipeable operations like map and chain using the pipeable function:

import { pipeable } from 'fp-ts/lib/pipeable';

const { map, chain } = pipeable(monadStackInstance);
prescientmoon commented 4 years ago

Thanks a lot @aqrln. Is there also a good way of creating a helper which intialized the stack containing a left?

aqrln commented 4 years ago

I think you’d need to define it manually, unfortunately. Everything that follows from all of the monads in the stack being monads should be in the resulting monad instance, but everything that follows from the semantics and not the general laws can’t be automated easily, I believe, so one has to compose functions the way it makes sense (when such composition exists at all). You may look at some predefined monad stacks (e.g., https://github.com/gcanti/fp-ts/blob/master/src/StateReaderTaskEither.ts) to draw inspiration from, but as you can see, there’s quite a bit of boilerplate there.

aqrln commented 4 years ago

But then again, I don’t have very much experience with typed FP prior to fp-ts, so I sure may be missing something. I’d be curious how does it look like in, e.g., Scala’s Cats.

prescientmoon commented 4 years ago

@aqrln I see, thanks for the help:)

prescientmoon commented 4 years ago

I'd also like to mention that a prebuilt stack for Reader + State + Writer would be really nice, maybe even a getting started blog about Writer for begginers