Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Option.mapEffect for better native interoperability between Option and Effect. #4589

Open
anglinb opened this issue Mar 11, 2025 · 2 comments
Labels
enhancement New feature or request

Comments

@anglinb
Copy link
Contributor

anglinb commented Mar 11, 2025

What is the problem this feature would solve?

I frequently want to take an option like Option.Option<number> and apply some effect to the result to turn that option into Option.Option<Effect.Effect<Something>> but the options to do so feel really clunky in comparison to a simple Option.mapEffect call.

Here's a breakdown of the existing ways I've tried to solve the issue: https://effect.website/play#be67835bcf4d

What is the feature you are proposing to solve the problem?

My proposed solution would look like this:

// Proposed new implementation
const mapEffect = <Value, S, F, C>(
  option: Option.Option<Value>,
  effect: (some: Value) => Effect.Effect<S, F, C>
): Effect.Effect<Option.Option<S>, F, C> => {
  return Option.match(option, {
    onSome: (some) =>
      effect(some).pipe(
        Effect.map((s) => Option.some(s))
      ),
    onNone: () => Effect.succeed(Option.none<S>()) as Effect.Effect<Option.None<S>, F, C>
  })
}

Here's a full example: https://effect.website/play#be67835bcf4d

What alternatives have you considered?

I've tried unwrapping the option and catching and now using Effect.transposeOption but I still think this simple api would make for a much nicer one-liner for dealing with this situation.

@anglinb anglinb added the enhancement New feature or request label Mar 11, 2025
@gcanti
Copy link
Contributor

gcanti commented Mar 11, 2025

I think Effect.transposeOption should be sufficient, as mapEffect is essentially just Option.map combined with transposeOption:

import { Effect, Option } from "effect"

const mapEffect = <Value, S, F, C>(
  option: Option.Option<Value>,
  f: (some: Value) => Effect.Effect<S, F, C>
) => {
  return option.pipe(
    Option.map(f),
    Effect.transposeOption
  )
}

@anglinb
Copy link
Contributor Author

anglinb commented Mar 11, 2025

I agree, was just hoping to combine those two lines into one API since 1) I use it very frequently and 2) to improve discoverability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants