A central concept in functional languages is that the result of a function is determined by its input, and only by its input. There are no side-effects!
— Why Haskell matters
My question is, if a function makes changes only within its local environment, and returns the result, how can it interact with a database or a file system? By definition, wouldn’t that be accessing what is in effect a global variable or global state?
What is the most common pattern used to get around or address this?
— edited Dec 7 ’11 at 2:10, Matt Fenwick
— asked Dec 6 ’11 at 20:18, juwiley
The most common pattern for dealing with side-effects and impurity in functional languages is:
- be pragmatic, not a purist
- provide built-ins that allow impure code and side-effects
- use them as little as possible!
- Clojure: refs, and using mutating methods on java objects
- Scala: creating variables with
- ML: not sure of specifics, but Wikipedia says it allows some impurity
Haskell cheats a little bit — its solution is that for functions that access the file system, or the database, the state of the entire universe at that instant, including the state of the filesystem/db, will be passed in to the function.(1) Thus, if you can replicate the state of the entire universe at that instant, then you can get the same results twice from such a function. Of course, you can’t replicate the state of the entire universe at that instant, and so the functions return different values …
But Haskell’s solution, IMHO, is not the most common.
(1) Not sure of the specifics here. Thanks to CAMcCann for pointing out that this metaphor is overused and maybe not all that accurate.
— edited Dec 7 ’11 at 2:11
— answered Dec 6 ’11 at 22:00, Matt Fenwick
— Stack Overflow
2012.08.12 Sunday ACHK