Karanveer Plaha wrote:Hi Alexander,
In my work I've encountered scripts and automations which are a collection of imperative functions which are called exclusively for their side effects.
They are composed entirely of I/O steps (fetching data from database, posting to another service, writing logs to file) which are also sequential in terms of time.
What strategies could be applied to begin to make these kinds of imperative programs more functional?
Hi Karanveer Plaha, thank you for your question!
FP developers have a long history of going into the pure world of avoiding side effects. FP has much more practices of pure data transformation rather than practices of dealing with the impure, unreliable real world. But we can't write useful programs without dealing with side effects, and the bigger and more complex the application is, the more problems are coming from the interaction with the external world. This is clear to me that FP can't be different here from other paradigms.
So, in FP, we started inventing approaches to this. Many Haskell programs do imperative IO explicitly and use different architectural
patterns like Service Handle or ReaderT. IO is monadic in Haskell, this means it's sequential. There are other approaches like effect systems, Final Tagless/mtl and just a bare IO. In my book, I'm showing almost all of these approaches, and proposing my own based on Free monads. Its idea is that you can encode your actions purely in Free monadic eDSLs, and then you get the sequential / imperative-like property because of monads. Interestingly, your business logic code will stay pure, because it will be encoding DB operations, logs etc., and real actions will only happen on the implementation level.
This topic is a big part of my book. In the second half, I'm showing how to build a Free monadic framework that has all the needed things to write usual web backends and services. You can even checkout the related showcase project Hydra: a framework I built for my book. It was used as a prototype for creating more real-life technologies like EulerHS which are used in real production.
https://github.com/graninas/Hydra