4 ms·
"Side-effect free" doesn't mean there are no side-effects, it simply means that their existence is controlled, separated, and minimized. For instance, in Haskel
by tel 13y ago
"Side-effect free" doesn't mean there are no side-effects, it simply means that their existence is controlled, separated, and minimized. For instance, in Haskell, you have the pure function "unwords . map upcase . words" which, reading right to left as is the convention for function composition, breaks a string on whitespace, upcases each chunk, then glues them back together with spaces again. It's net signature is "String -> String".
By itself, this function is useless, but "interact" is a function with signature "(String -> String) -> IO ()" which means that it turns our "unwords . map upcase . words" into an interaction with the environment. There are whole debate here as to how interact is actually still pure, but for the purposes of this argument, interact is an impure effect.
The net program however is very simple: "interact (unwords . map upcase . words)". The pure part is decomposed into many other pure pieces, each with simple, small contracts and independent testability. The impure part also has a simple contract which is described in terms of pure computation.
Another great example is some of the streaming libraries available in Haskell today. Pipes for instance will let you compose a pipeline of pure and impure computations and have them work together nicely.
"fibsPipe >-> Pipes.take 20 >-> Pipes.print"
The first two segments are pure, but have empty "placeholder" slots for impure effects (identity monadic layers). These get merged seamlessly with the "Pipes.print" segment which has impure effects. All together, you get an infinite producer "fibsPipe" producing an impure effect "Pipes.print" while having its resource utilization and termination controlled by another pure computation "Pipes.take 20" which is actually maintaining its own implicit state (the current count of numbers it's let through).
But then you can decompose each piece and understand it on its own in a pure or simple impure fashion.