Purity vs Referential transparency

前端 未结 5 1964
旧时难觅i
旧时难觅i 2020-12-04 18:43

The terms do appear to be defined differently, but I\'ve always thought of one implying the other; I can\'t think of any case when an expression is referentially t

5条回答
  •  余生分开走
    2020-12-04 19:26

    All pure functions are necessarily referentially transparent. Since, by definition, they cannot access anything other than what they are passed, their result must be fully determined by their arguments.

    However, it is possible to have referentially transparent functions which are not pure. I can write a function which is given an int i, then generates a random number r, subtracts r from itself and places it in s, then returns i - s. Clearly this function is impure, because it is generating random numbers. However, it is referentially transparent. In this case, the example is silly and contrived. However, in, e.g., Haskell, the id function is of type a - > a whereas my stupidId function would be of type a -> IO a indicating that it makes use of side effects. When a programmer can guarantee through means of an external proof that their function is actually referentially transparent, then they can use unsafePerformIO to strip the IO back away from the type.

提交回复
热议问题