
On Saturday 16 October 2010 08:18:39, Jordan Ellis wrote:
I have a quick follow-up question: With optimization enabled, will a value be shared between recursive function calls? For example, in the following: myRecursiveFunction 0 m = [] myRecursiveFunction n m = m : myRecursiveFunction (n - 1) m ...will 'm' be calculated 'n' times, or just once? Thanks.
Here, you don't have two equal expressions, the m refers to the same entity in both appearances on the RHS. It's not guaranteed by the language definition, but every decent implementation will evaluate m only once (all occurrences are pointers to the same heap object, so you get n pointers, but only one pointed-to value). With or without optimisation. That's of course bad if m is large and you need a large part of it once at the beginning but only small parts afterwards, e.g. mapM_ (print . length) $ zipWith take (iterate (`quot` 2) 20000000) $ myRec n [1 .. k] To prevent that, if you don't want it, you have to jump through a couple of hoops.