Replacing applications of repeating functions with deterministic values

f x y z = [n | n <- z, n > x + y]

f 1 2 [3,4]

Will it be executed x + yonly once at first, so that successive calls are replaced with value 3? Is GHCHaskell optimized before this work for FP, gives us the power of referential transparency?

How to trace to prove it?

+4
source share
2 answers

I do not think the calculated value will be reused.

, x + y , , , , , . " ".

- , GHC , .

, GHC Core, . , . ( , !) , , ! (I.e., -O2.)

f x y z = let s = x + y in [ n | n <- z, n > s ]

s . (1.e., f. , f, s.)

, , , , "memoisation".

+9

, , ghci vs. ghc, , , .

:

import Debug.Trace

f x y z = [n | n <- z, n > tx x + ty y]
  where tx = trace "x"
        ty = trace "y"

main = print $ f 1 2 [3,4]

7.8.3 :

  • ghci: x y x y [4]
  • ghc ( ): x y x y [4]
  • ghc -O2: x y [4]

, trace CSE. , -O2 x+y .

+6

All Articles