Functional Programming – How Referential Transparency is Enforced

functional programmingprogramming-languagesside-effect

In FP languages, calling a function with the same parameters over and over again returns the same result over and over again (i.e. referential transparency).

But a function like this (pseudo-code):

function f(a, b) {
    return a + b + currentDateTime.seconds;
}

is not going to return the same result for the same parameters.

How are these cases handled in FP?

How is referential transparency enforced? Or is it not and it depends on the programmers to behave themselves?

Best Answer

a and b are Numbers, whereas currentDateTime.seconds returns an IO<Number>. Those types are incompatible, you cannot add them together, therefore your function is not well-typed and simply won't compile. At least that's how it's done in pure languages with a static type system, like Haskell. In impure languages like ML, Scala or F#, it is up to the programmer to ensure referential transparency, and of course in dynamically typed languages like Clojure or Scheme, there is no static type system to enforce referential transparency.