Programming style question

Adrian Hey ahey@iee.org
Fri, 11 Jan 2002 20:09:30 +0000


On Friday 11 January 2002  8:46 am, D. Tweed wrote:
> Even sillier question: there's no other way of getting the optimization
> that normCorr' has over normCorr (as always on the understanding it may
> be a space leak) in Haskell?
>
> dotProd xs ys=sum(zipWith (*) xs ys)
>
> normCorr :: Floating a => [a] -> [a] -> a
> normCorr xs ys =(dotProd xs ys)/(sqrt((dotProd xs xs)*(dotProd ys ys)))
>
> normCorr' :: Floating a => [a] -> [a] -> a
> normCorr' xs=let e=sqrt(dotProd xs xs)
>              in \ys->(dotProd xs ys)/(e*(sqrt(dotProd ys ys)))
>
> for use in, say, corrWithSimpleSignal = normCorr' [1..100] (this is a
> contrived example I admit)
>
> I sometimes write such things but it doesn't leap out at me on rereading
> the code later why I've defined e only to have it used (on first glance)
> only once...

Well, apart from the fact that the compiler needs to know that
  sqrt (a*b)= (sqrt a)*(sqrt b) :-)
I think full laziness should effect the transformation.

But, IIRC a while ago Simon Marlow said that with ghc if you
have two adjacent lambdas and a free sub-expression which can be
lifted outside one but not the other (as in this case) then it
won't do the full laziness thing at all.

(But don't quote me on that because it's entirely possible
I misunderstood:-)

Regards
--
Adrian Hey