Type inference interferes with referential transparency

前端 未结 7 1322
醉酒成梦
醉酒成梦 2021-02-12 18:07

What is the precise promise/guarantee the Haskell language provides with respect to referential transparency? At least the Haskell report does not mention this notion.

C

7条回答
  •  借酒劲吻你
    2021-02-12 18:23

    What you think this has to do with referential transparency? Your uses of 7, ^, mod, 5, 2, and == are applications of those variables to dictionaries, yes, but I don't see why you think that fact makes Haskell referentially opaque. Often applying the same function to different arguments produces different results, after all!

    Referential transparency has to do with this expression:

    let x :: Int = 7^7^7`mod`5`mod`2 in (x == 1, [False, True] !! x)
    

    x is here a single value, and should always have that same single value.

    By contrast, if you say:

    let x :: forall a. Num a => a; x = 7^7^7`mod`5`mod`2 in (x == 1, [False, True] !! x)
    

    (or use the expression inline, which is equivalent), x is now a function, and can return different values depending on the Num argument you supply to it. You might as well complain that let f = (+1) in map f [1, 2, 3] is [2, 3, 4], but let f = (+3) in map f [1, 2, 3] is [4, 5, 6] and then say "Haskell gives different values for map f [1, 2, 3] depending on the context so it's referentially opaque"!

提交回复
热议问题