Programming style question

D. Tweed tweed@compsci.bristol.ac.uk
Fri, 11 Jan 2002 08:46:59 +0000 (GMT)


On Thu, 10 Jan 2002, Mark P Jones wrote:

> | If I have defined a function like this..
> | 	f <args> = <blah> <args>
> | it could be re-written..
> | 	f = <blah>
[snip]
> - The second will compute a value of <blah> at most
>   once, then cache the result for future use.  That
>   could make a program run faster, but if the result
>   of <blah> takes a lot of space, then it could result
>   in a space leak.  The first might end up repeating
>   the computation of <blah> each time f is called.
[snip] 
>   Denotationally, the two expressions are the same.
>   (In other words, they both produce the same value.)
>   But the example above shows an operational difference
>   in some implementation.  (As far as I can tell, however,
>   nothing in the language definition either guarantees or
>   prevents such behavior.)

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...

___cheers,_dave_________________________________________________________
www.cs.bris.ac.uk/~tweed/|`...heat generated by its microprocessors will
email:tweed@cs.bris.ac.uk|slope upward exponentially, reaching the power
work tel:(0117) 954-5250 |density of a nuclear reactor before 2010'-Intel