[Haskell-cafe] Using Product Algebraic types

Sven Panne Sven.Panne at aedion.de
Sun Jul 4 17:11:30 EDT 2004


David Menendez wrote:
> [...] If that turned out to be a performance bottleneck, you could factor out
> pair and write f directly: [...]

... or directly complain to your compiler supplier if the compiler in question
does not do this simple transformation for you. :-)

<sigh>
    I always get a bad feeling when people start to think about efficiency right
    from the beginning: First get your program correct and readable, then measure,
    and only then optimize (if at all). Programmers are notoriously bad when
    guessing about efficiency, which even more true for lazy functional programs.
</sigh>

Let's e.g. have a look at the code generated by GHC for the "inefficient" version:

---------------------------------------------------------------------------------
helper :: (Fitness, a) -> (Fitness, a) -> (Fitness, a)
helper = \ds eta ->
    case ds of
       (f, a) -> case eta of
                    (g, b) -> (g `plusInteger` f, b)

rw :: Population a -> Population a
rw = \ds ->
    case ds of
       Population xs ->
          Population (case xs of
                         (x:xs1) -> scanl helper x xs1
                         [] -> [])
---------------------------------------------------------------------------------

Or in a more readable, but equivalent, form:

---------------------------------------------------------------------------------
helper :: (Fitness, a) -> (Fitness, a) -> (Fitness, a)
helper (f, a) (g, b) = (g `plusInteger` f, b)

rw :: Population a -> Population a
rw (Population xs) = Population (case xs of
                                    (x:xs1) -> scanl helper x xs1
                                    [] -> [])
---------------------------------------------------------------------------------

What has happened? `pair', `id', and `scanl1' were completely inlined and instead
of the overloaded (+), an Integer-specific addition was chosen (`plusInteger',
it's not the real name, just something for presentation purposes). Although these
are all only O(1) optimizations (nothing "really clever"), one can hardly do better
by hand... So keep the program in a form which is most comprehensible, even if
this seems to imply some "superfluous" things at first. This enables you to have
more time for more interesting things which could really have some effect on
performance, like clever algorithms etc.

Cheers,
    S.



More information about the Haskell-Cafe mailing list