[Haskell-cafe] FP design

Thomas Schilling nominolo at googlemail.com
Tue Nov 6 14:44:02 EST 2007


On Tue, 2007-11-06 at 10:32 +1030, Levi Stephen wrote:
> Hi,
> 
> I'm was wondering how most people work during when designing a functional 
> program. Do you create data structures/types first? Do you work from some type 
> signatures?

As others have mentioned: both.  But there's a third thing that you can
do, other than start implementing:  think about the laws/properties that
should hold.  That's not always simple, in fact, it rarely is.  But it
helps you get one step closer to what you need to implement.  If you can
find useful properties, though, you get lots of test-cases for free by
formulating and testing them using QuickCheck.

Then, when implementing, you probably realize that you might need some
more combinators.  I usually then stop and implement the combinator
first, test it and continue.  

Some other guidelines I recommend: 

 * Try not to be too abstract in the first place.  Try implementing a
specialized version first, and then see how you can abstract it, once
you implemented all facets.  Sometimes, you need to add some instance
constraints, but the compiler will tell you where.

 * Test early and often.  Note that in Haskell you can get the compiler
to typecheck successfully by adding dummy-definitions using "_" and
"undefined".  E.g.:

    foo :: A -> B -> C
    foo _ _ = undefined

 * Define abstract types, or at least type synonyms.  It's so easy to
define new abstract types in Haskell, that you should do it often.  This
makes it much easier to later choose the proper data structure, once you
know what details you need.  Also, it's implicit documentation, compare

    type Author = String;  type Title = String
    addPost :: Author -> Title -> String -> Blog -> Blog

and

    addPost :: String -> String -> String -> Blog -> Blog

 * Think about complexity of your primitives.  This is hard to fix
later, so it should be taken into account early on.  Of course, there's
sometimes a fine line between mature and premature optimizations.

 * As Don often says, try to keep things pure wherever possible.  It
will make your code so much more compositional, easier to test and
correct.

There's more, but I'll stop here for now...




More information about the Haskell-Cafe mailing list