[Haskell-beginners] When, if ever, does Haskell "calculate once"?

Travis Erdman traviserdman at yahoo.com
Thu May 6 14:35:15 EDT 2010

Two questions here, I think they might be related, perhaps even the same, but I am not sure, so I will ask both:

Q1:  Re the function f below, I like the first implementation as it's "cleaner", but is the second implementation necessary for performance purposes?

-- g = some CPU intensive function

-- alternate 1
f a b = c + (g b)
        c = dosomethingelse a (g b)
-- alternate 2        
f a b = c + saveit
        saveit = g b    
        c = dosomethingelse a saveit

Q2:  Imagine that I might be creating a custom data structure.  I need to access both the data in that structure, but also "features" (don't know proper comp sci term) of the data structure.  For instance, consider a Haskell list.  The stuff in the list is the data, whereas the length of the list is what I am calling a "feature" here.  Some of my features might be quite a bit more computationally intensive than "length", and may be referenced multiple times in many different places in my code.  For performance purposes, should I consider modifying my data structure to embed these "features" as part of the data to ensure that it is only calculated once?  Or can I rely on Haskell to do that for me?  For instance, do I need to create the equivalent of:

data MyList a = MyList {mylist::[a], mylength::Int}

Thanks again for all your generous advice.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100506/2b3fc6f6/attachment.html

More information about the Beginners mailing list