r/functionalprogramming • • Aug 02 '25

Question Strategies for Functional Programming in IO-heavy Programs?

Hi all, long time appreciator of this sub! Ive studied some type theory and tried learning functional programming independently. One question that persists is how do you keep with the functional paradigm when the program you're working with involves lots of IO at many stages of the process and the spaces between where everything is just transforming data are relatively thin?

For context, I was helping some coworkers with a Python SDK wrapping some of our backend APIs. Many of their functions required hitting an end point a couple times, short bits of operating on the results, then sending those results to other APIs, rinse and repeat in sequence. From reading Frisby's Guide to Functional Programming in JavaScript (feel free to toss some recs if you want), I know you can use lazy evaluation and monads to manage IO and put off execution/side effects, but since a lot of the code is gluing together API calls it feels like this could get unwieldy quickly.

What do y'all usually do to manage highly side effectful code in a functional style? Is this a "don't let a paradigm get in the way of doing the task" kind of situation? Is this when you have to pay the cost of a decent bit of boilerplate in exchange for keeping with a functional style (lots of monads, handling nested monads, chaining, etc)? Feel free to cite/link to specific examples or libraries, I do want to learn general strategies to the problem however for when I'm in a language like Python or Go where functional libraries solving this problem may not be prevalent.

35 Upvotes

25 comments sorted by

View all comments

Show parent comment

5

u/layaryerbakar Aug 03 '25 edited Aug 03 '25

In haskell you just need a single IO like

myFunction :: IO V
myFunction = do
    let arr = [t1, t2, t3]
    
    results1 <- traverse effectful_fn1 arr
    
    let next_input = some_function_1 results1
    
    last_result <- effectful_fn2 next_input
    
    let output = some_function_2 last_result
    pure output

You have to use bind (<-) to sequence effectful computation while pure function with let. This way you wouldn't ended up with nested IO. traverse is used if you have collections of input you want to transform through an effectul function. It will handle sequenceing the effectful computation so the overall result could be a single IO computation.

In language like python or typescript that doesn't have do notation, the fp library probably provide a monad interface with bind for effectful function and some sort of traverse for collection (mind you they could be name differently like andThen and forEach or entirely different things depending on the library). They will be verbose that's why I'd just do imperative style in those language

2

u/layaryerbakar Aug 03 '25

I just skimmed through Frisby's Adequate Guide and there bind was called chain and traverse still called traverse