[clean-list] local functions as CAF

Ronny Wichers Schreur ronny@cs.kun.nl
Mon, 26 Mar 2001 15:19:51 +0100


Paul de Mast writes (to the Clean Discussion list):

>Start = filter f [1..10]
>where
>       f x = x > y
>       where
>               y =  2*3  // or a complex calculation
>
>If we put y on the same level as f y is evaluated only once:
> 
>Start = filter f [1..10]
>where
>       f x = x > y
>
>       y =  2*3  // or a complex calculation
>
>Is it possible that the compiler optimises the first situation
>by lifting y to the same level as f?

No, the compiler can't do that (in general).

Introducing sharing is not always an optimisation. Sometimes
it can be cheaper to re-evaluate than to keep the (partially)
evaluated expression. Lifting a variable also comes at a price.
The function f will get an extra argument (more difficult to
generate efficient code), building the closure for filter's
predicate will be more expensive. How should the compiler infer
how many times filter's predicate will be called?

In any case, I don't see why you would want to do that. To me
the two different versions exactly reflect what's going on,
especially if you manually lift the variable y in the second
function (as I prefer):

    Start
        =   filter (f y) [1..10]
        where
           y =  2*3  // or a complex calculation

           f y x
                =   x > y

So sharing if you specify it, no sharing if you don't.
Power to the programmer!



Cheers,

Ronny Wichers Schreur