Effect CommunityEC
Effect Community13mo ago
2 replies
AndersR

How does one pass argument values to Effect.gen?

In a pipeline I can initiate that pipe with some initial input value. How would I do the equivalent with a generator flow? All the examples in the docs (https://effect.website/docs/getting-started/using-generators/) have hard-coded input values. What would be an example of passing in a variable? For example, in the docs we have this:

import { Effect } from "effect"

const addServiceCharge = (amount: number) => amount + 1

const applyDiscount = (
  total: number,
  discountRate: number
): Effect.Effect<number, Error> =>
  discountRate === 0
    ? Effect.fail(new Error("Discount rate cannot be zero"))
    : Effect.succeed(total - (total * discountRate) / 100)

const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))

const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))

export const program = Effect.gen(function* () {
  const transactionAmount = yield* fetchTransactionAmount
  const discountRate = yield* fetchDiscountRate
  const discountedAmount = yield* applyDiscount(
    transactionAmount,
    discountRate
  )
  const finalAmount = addServiceCharge(discountedAmount)
  return `Final amount to charge: ${finalAmount}`
})


As you can see, here the transaction amount is hard-coded. What if I wanted to be able to pass in that value as a variable? Btw, this all feels very basic so I am wondering if there is something fundamental I am missing here. Thanks for any insights!
Effect Documentation
Learn how to use generators in Effect for writing effectful code, enhancing control flow, handling errors, and simplifying asynchronous operations with a syntax similar to async/await.
Using Generators
Was this page helpful?