Search code examples
haskellreferential-transparency

Why does the use of functions defined in outer scope not break referential transparency?


I am learning Haskell. If I understand correctly, a simple function in Haskell is always referentially transparent. I thought it means its output depends only on the arguments passed to it.

But a function f can call another function g, defined in the outer scope. So in that sense, f's return value depends on the definition of g. And the function g is not passed to f as a parameter - at least not explicitly. Doesn't this break referential transparency?


Solution

  • Referential transparency means that

    f s = "Hello " ++ g s
    g s = s ++ "!"
    

    is indistinguishable from

    f s = "Hello " ++ h s
      where h s = s ++ "!"
    g s = s ++ "!"
    

    and

    f s = "Hello " ++ s ++ "!"
    g s = s ++ "!"
    

    It means you can inline g into f without it altering the meaning of f.

    If it was going to alter the meaning of f, you would have to alter g somehow. How?