简体   繁体   中英

Evaluation of a function in other functions with same parameters in Haskell

Consider the toy example below:

someNum :: Int
someNum = 42

funcCommon :: Int -> Int
funcCommon x = x + 1

func1 :: Int -> (Int -> Int) -> Int
func1 x f = f x

func2 :: Int -> (Int -> Int) -> Int
func2 x f = f x

f1 = func1 someNum funcCommon 
f2 = func2 someNum funcCommon 

main = do
  print f1
  print f2

The same arguments funcCommon and someNum get applied as a parameters to both func1 and func2 so we get a situation where func1 and func2 are declared separately (are different functions) but both end up calling the same function with the same argument. How many times then does funcCommon someNum get actually evaluated? Does the result get reused and there is only one evaluation of funcCommon someNum ?

The language does, strictly speaking, not define whether it's evaluated once, twice, or 37 times, or what it even means to evaluate something a particular number of times. All it does guarantee is that the strictness rules are obeyed, ie with

f1, f2 :: [Int]
f1 = repeat 1
f2 = error "evil"

main = do
  print f1
  print f2

you could be sure that the error isn't triggered because printing f1 will actually just forever spit out 1 digits and thus f2 is evaluated exactly zero times.

For some particular situations, the compiler could actually do all the computations for f1 and f2 at compile-time and neither of them would be “evaluated” at runtime at all.

In practice, you should expect two evaluations to happen . Confirming that two functions do the same thing is a hard problem, so the compiler generally won't bother.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM