r/functionalprogramming • u/ginkx • Feb 11 '24
Question Containing effects in a non-pure language like C++
I think Haskell's idea of controlling mutability through ST Monads is great. But I am not always writing code in Haskell or a purely functional language for reasons that are outside my control right now. So I do not always have the luxury of ST Monad while writing code in a language like C++.
Of course I could always never mutate, always copy every variable to have purity. However, this is suboptimal in terms of space and computations for datastructures like arrays. To resolve this dilemna, I was wondering if there were any abstract constructs that would help me mutate variables but contain their effects in a language like C++.
I would appreciate any pointers or references even if it's not a complete answer.
7
u/TechnoEmpress Feb 11 '24
If your runtime system is not tailored for immutability and litters your code with
free()(instead of doing a more efficient form of garbage collection), you are going to have a very bad time trying to emulate a pure FP language :(4
u/pthierry Feb 11 '24
You're not the first to wish using immutable data structures in C++, there's a whole library for that:
https://github.com/arximboldi/immer
2
u/dogweather Feb 12 '24
Maybe delegate all mutation to an external service like Postgres?
I dunno, I’m kind of new at this. I’ve never understood Haskell’s ST Monad well enough to use it.
6
u/GunpowderGuy Feb 11 '24 edited Feb 11 '24
C++ can't even Ensure safety, you can forget about containing side effects