Search code examples
clojureside-effects

The meaning of side-effect in Clojure


I was thinking on the meaning of side-effect in Clojure. What exactly is a side-effect in Clojure? Could any one explain this with an example?


Solution

  • A side effect in any programming language would be everything that is done which does not have a direct correlation between supplied arguments and the returned result.

    (+ 3 4)      ; ==> 7 (result is always a mapping between arguments and result. It will always be 7 no matte rhow many times you do it. 
    (rand-int 4) ; ==> 0,1,2, or 3. You have no idea what it will produce next. 
    

    The first expression is functional. You can make a lookup table of all the different two values with it's result and you wouldn't know the difference.

    The second might give different result for the same argument. The computation must be based on something else, like internal state, and not the argument alone. It has side effects.

    Typical side effects used in programs are I/O and object mutation.