Large-scale design in Haskell?

61,033

Solution 1

I talk a bit about this in Engineering Large Projects in Haskell and in the Design and Implementation of XMonad. Engineering in the large is about managing complexity. The primary code structuring mechanisms in Haskell for managing complexity are:

The type system

  • Use the type system to enforce abstractions, simplifying interactions.
  • Enforce key invariants via types
    • (e.g. that certain values cannot escape some scope)
    • That certain code does no IO, does not touch the disk
  • Enforce safety: checked exceptions (Maybe/Either), avoid mixing concepts (Word, Int, Address)
  • Good data structures (like zippers) can make some classes of testing needless, as they rule out e.g. out of bounds errors statically.

The profiler

  • Provide objective evidence of your program's heap and time profiles.
  • Heap profiling, in particular, is the best way to ensure no unnecessary memory use.

Purity

  • Reduce complexity dramatically by removing state. Purely functional code scales, because it is compositional. All you need is the type to determine how to use some code -- it won't mysteriously break when you change some other part of the program.
  • Use lots of "model/view/controller" style programming: parse external data as soon as possible into purely functional data structures, operate on those structures, then once all work is done, render/flush/serialize out. Keeps most of your code pure

Testing

  • QuickCheck + Haskell Code Coverage, to ensure you are testing the things you can't check with types.
  • GHC + RTS is great for seeing if you're spending too much time doing GC.
  • QuickCheck can also help you identify clean, orthogonal APIs for your modules. If the properties of your code are difficult to state, they're probably too complex. Keep refactoring until you have a clean set of properties that can test your code, that compose well. Then the code is probably well designed too.

Monads for Structuring

  • Monads capture key architectural designs in types (this code accesses hardware, this code is a single-user session, etc.)
  • E.g. the X monad in xmonad, captures precisely the design for what state is visible to what components of the system.

Type classes and existential types

  • Use type classes to provide abstraction: hide implementations behind polymorphic interfaces.

Concurrency and parallelism

  • Sneak par into your program to beat the competition with easy, composable parallelism.

Refactor

  • You can refactor in Haskell a lot. The types ensure your large scale changes will be safe, if you're using types wisely. This will help your codebase scale. Make sure that your refactorings will cause type errors until complete.

Use the FFI wisely

  • The FFI makes it easier to play with foreign code, but that foreign code can be dangerous.
  • Be very careful in assumptions about the shape of data returned.

Meta programming

  • A bit of Template Haskell or generics can remove boilerplate.

Packaging and distribution

  • Use Cabal. Don't roll your own build system. (EDIT: Actually you probably want to use Stack now for getting started.).
  • Use Haddock for good API docs
  • Tools like graphmod can show your module structures.
  • Rely on the Haskell Platform versions of libraries and tools, if at all possible. It is a stable base. (EDIT: Again, these days you likely want to use Stack for getting a stable base up and running.)

Warnings

  • Use -Wall to keep your code clean of smells. You might also look at Agda, Isabelle or Catch for more assurance. For lint-like checking, see the great hlint, which will suggest improvements.

With all these tools you can keep a handle on complexity, removing as many interactions between components as possible. Ideally, you have a very large base of pure code, which is really easy to maintain, since it is compositional. That's not always possible, but it is worth aiming for.

In general: decompose the logical units of your system into the smallest referentially transparent components possible, then implement them in modules. Global or local environments for sets of components (or inside components) might be mapped to monads. Use algebraic data types to describe core data structures. Share those definitions widely.

Solution 2

Don gave you most of the details above, but here's my two cents from doing really nitty-gritty stateful programs like system daemons in Haskell.

  1. In the end, you live in a monad transformer stack. At the bottom is IO. Above that, every major module (in the abstract sense, not the module-in-a-file sense) maps its necessary state into a layer in that stack. So if you have your database connection code hidden in a module, you write it all to be over a type MonadReader Connection m => ... -> m ... and then your database functions can always get their connection without functions from other modules having to be aware of its existence. You might end up with one layer carrying your database connection, another your configuration, a third your various semaphores and mvars for the resolution of parallelism and synchronization, another your log file handles, etc.

  2. Figure out your error handling first. The greatest weakness at the moment for Haskell in larger systems is the plethora of error handling methods, including lousy ones like Maybe (which is wrong because you can't return any information on what went wrong; always use Either instead of Maybe unless you really just mean missing values). Figure out how you're going to do it first, and set up adapters from the various error handling mechanisms your libraries and other code uses into your final one. This will save you a world of grief later.

Addendum (extracted from comments; thanks to Lii & liminalisht) —
more discussion about different ways to slice a large program into monads in a stack:

Ben Kolera gives a great practical intro to this topic, and Brian Hurt discusses solutions to the problem of lifting monadic actions into your custom monad. George Wilson shows how to use mtl to write code that works with any monad that implements the required typeclasses, rather than your custom monad kind. Carlo Hamalainen has written some short, useful notes summarizing George's talk.

Solution 3

Designing large programs in Haskell is not that different from doing it in other languages. Programming in the large is about breaking your problem into manageable pieces, and how to fit those together; the implementation language is less important.

That said, in a large design it's nice to try and leverage the type system to make sure you can only fit your pieces together in a way that is correct. This might involve newtype or phantom types to make things that appear to have the same type be different.

When it comes to refactoring the code as you go along, purity is a great boon, so try to keep as much of the code as possible pure. Pure code is easy to refactor, because it has no hidden interaction with other parts of your program.

Solution 4

I did learn structured functional programming the first time with this book. It may not be exactly what you are looking for, but for beginners in functional programming, this may be one of the best first steps to learn to structure functional programs - independant of the scale. On all abstraction levels, the design should always have clearly arranged structures.

The Craft of Functional Programming

The Craft of Functional Programming

http://www.cs.kent.ac.uk/people/staff/sjt/craft2e/

Solution 5

I'm currently writing a book with the title "Functional Design and Architecture". It provides you with a complete set of techniques how to build a big application using pure functional approach. It describes many functional patterns and ideas while building an SCADA-like application 'Andromeda' for controlling spaceships from scratch. My primary language is Haskell. The book covers:

  • Approaches to architecture modelling using diagrams;
  • Requirements analysis;
  • Embedded DSL domain modelling;
  • External DSL design and implementation;
  • Monads as subsystems with effects;
  • Free monads as functional interfaces;
  • Arrowised eDSLs;
  • Inversion of Control using Free monadic eDSLs;
  • Software Transactional Memory;
  • Lenses;
  • State, Reader, Writer, RWS, ST monads;
  • Impure state: IORef, MVar, STM;
  • Multithreading and concurrent domain modelling;
  • GUI;
  • Applicability of mainstream techniques and approaches such as UML, SOLID, GRASP;
  • Interaction with impure subsystems.

You may get familiar with the code for the book here, and the 'Andromeda' project code.

I expect to finish this book at the end of 2017. Until that happens, you may read my article "Design and Architecture in Functional Programming" (Rus) here.

UPDATE

I shared my book online (first 5 chapters). See post on Reddit

Share:
61,033
Dan
Author by

Dan

Student. Learning.

Updated on July 09, 2022

Comments

  • Dan
    Dan almost 2 years

    What is a good way to design/structure large functional programs, especially in Haskell?

    I've been through a bunch of the tutorials (Write Yourself a Scheme being my favorite, with Real World Haskell a close second) - but most of the programs are relatively small, and single-purpose. Additionally, I don't consider some of them to be particularly elegant (for example, the vast lookup tables in WYAS).

    I'm now wanting to write larger programs, with more moving parts - acquiring data from a variety of different sources, cleaning it, processing it in various ways, displaying it in user interfaces, persisting it, communicating over networks, etc. How could one best structure such code to be legible, maintainable, and adaptable to changing requirements?

    There is quite a large literature addressing these questions for large object-oriented imperative programs. Ideas like MVC, design patterns, etc. are decent prescriptions for realizing broad goals like separation of concerns and reusability in an OO style. Additionally, newer imperative languages lend themselves to a 'design as you grow' style of refactoring to which, in my novice opinion, Haskell appears less well-suited.

    Is there an equivalent literature for Haskell? How is the zoo of exotic control structures available in functional programming (monads, arrows, applicative, etc.) best employed for this purpose? What best practices could you recommend?

    Thanks!

    EDIT (this is a follow-up to Don Stewart's answer):

    @dons mentioned: "Monads capture key architectural designs in types."

    I guess my question is: how should one think about key architectural designs in a pure functional language?

    Consider the example of several data streams, and several processing steps. I can write modular parsers for the data streams to a set of data structures, and I can implement each processing step as a pure function. The processing steps required for one piece of data will depend on its value and others'. Some of the steps should be followed by side-effects like GUI updates or database queries.

    What's the 'Right' way to tie the data and the parsing steps in a nice way? One could write a big function which does the right thing for the various data types. Or one could use a monad to keep track of what's been processed so far and have each processing step get whatever it needs next from the monad state. Or one could write largely separate programs and send messages around (I don't much like this option).

    The slides he linked have a Things we Need bullet: "Idioms for mapping design onto types/functions/classes/monads". What are the idioms? :)

  • Dan
    Dan almost 14 years
    Thanks Don, your answer is excellent - these are all valuable guidelines and I will refer to them regularly. I guess my question occurs a step before one would need all this, though. What I'd really like to know are the "Idioms for mapping design onto types/functions/classes/monads" ... I could try to invent my own, but I was hoping there might be a set of best practices distilled somewhere - or if not, recommendations for well-structured code to read of a large-ish system (as opposed to, say, a focused library). I edited my post to ask this same question more directly.
  • Don Stewart
    Don Stewart almost 14 years
    I've added some text on decomposition of design to modules. Your goal is to identify logically related functions into modules that have referentially transparent interfaces with other parts of the system, and to use purely functional data types as soon as possible, as much as possible, to model the outside world safely. The xmonad design document covers a lot of this: xmonad.wordpress.com/2009/09/09/…
  • Dan
    Dan almost 14 years
    Thanks again! The xmonad design document is just what I was looking for. Time to read some code...
  • Joseph Garvin
    Joseph Garvin almost 14 years
    One thing that I think could be added to this question is an explanation of how Haskell helps you avoid giant switch/case statements. In an OOP language whenever you see one it's a sign you should be using polymorphism and virtual functions, and it's one of the basic mechanisms through which OOP helps code scale, even just by helping physical layout -- all those case handlers when redone as virtual functions are going to belong in different classes with their own files. But how do you avoid the giant switch/case in Haskell? I think this is what the OP is getting at as regards the WYAS tables.
  • Don Stewart
    Don Stewart almost 14 years
    Hmm. Giant switches? Haven't seen those in Haskell. Don't we just dispatch to type class methods?
  • Joseph Garvin
    Joseph Garvin almost 14 years
    I'm no Haskell expert but I thought type class methods couldn't be virtual? The giant switches you see in C like languages are for runtime polymorphism, and usually the better alternative is to use virtual methods. If I understand Haskell type classes correctly, at a given call site which version of a type class method will be called is fixed at compile time.
  • Don Stewart
    Don Stewart almost 14 years
    Sometimes the type isn't known statically, so a dictionary of methods is supplied as a parameter (in GHC's dictionary-passing implementation).
  • Dan
    Dan almost 14 years
    I actually found that refactoring is quite frustrating, if the data types need to change. It requires tediously modifying the arity of lots of constructors and pattern-matches. (I agree that refactoring pure functions into other pure functions of the same type is easy - as long as one doesn't touch the data types)
  • mik01aj
    mik01aj over 13 years
    I tried to download the slides from the Engineering Large Projects in Haskell talk, but the link appeared to be broken. Here's a working one: galois.com/~dons/talks/dons-londonhug-decade.pdf
  • Don Stewart
    Don Stewart about 13 years
    As great as the Craft of FP is -- I learned Haskell from it -- it is an introductory text for beginner programmers, not for the design of large systems in Haskell.
  • comonad
    comonad almost 13 years
    Well, It is the best book I know about designing APIs and hiding implementation details. With this book, I became a better programmer in C++ — just because I learned better ways to organize my code. Well, your experience (and answer) is surely better than this book, but Dan might probably still be a beginner in Haskell. (where beginner=do write $ tutorials `about` Monads)
  • Riccardo T.
    Riccardo T. over 12 years
    The dowload link at xmonad.wordpress.com/2009/09/09/… for the slides does not work :(
  • Riccardo T.
    Riccardo T. over 12 years
    I managed to found this new download link: pau-za.cz/data/2/sprava.pdf
  • jameshfisher
    jameshfisher almost 11 years
    I find this comment interesting: "Make sure that your refactorings will cause type errors until complete."
  • Lii
    Lii over 10 years
    Two good points! This answer has the merit of being reasonably concrete, something that the other ones are not. It would be interesting to read more discussion about different ways to slice a large program into monads in a stack. Please post links to such articles if you have any!
  • Lii
    Lii over 10 years
    This answer gives many good pieces of advice, but most are fairly obvious, like "use purity", "use the type system", "be careful with the FFI". I agree with Dan that this topic "Monads capture key architectural designs in types" should have its own page long answer.
  • cnd
    cnd over 9 years
    @Riccardo now it's 404 too :(
  • Riccardo T.
    Riccardo T. over 9 years
    @Heather Even though the download link at the page I mentioned in the comment right before does not work, it looks like the slides can still be viewed on scribd: scribd.com/doc/19503176/The-Design-and-Implementation-of-xmo‌​nad
  • MasterMastic
    MasterMastic over 9 years
    @Dan You can get away completely free with smaller changes (like just adding a field) when you use records. Some may want to make records a habit (I'm one of them ^^").
  • semicolon
    semicolon about 8 years
    @Dan I mean if you change the data type of a function in any language don't you have to do the same? I don't see how a language such as Java or C++ would help you in this regard. If you say that you can use some sort of common interface that both types obey then you should have been doing that with Typeclasses in Haskell.
  • liminalisht
    liminalisht about 8 years
    @Lii Ben Kolera gives a great practical intro to this topic, and Brian Hurt discusses solutions to the problem of lifting monadic actions into your custom monad. George Wilson shows how to use mtl to write code that works with any monad that implements the required typeclasses, rather than your custom monad kind. Carlo Hamalainen has written some short, useful notes summarizing George's talk.
  • liminalisht
    liminalisht almost 8 years
    I would mention another post by Gabriel Gonzalez on the category design pattern. His basic argument is that what we functional programmers think of as "good architecture" is really "compositional architecture" - it's designing programs using items that are guaranteed to compose. Since the category laws guarantee that identity and associativity are preserved under composition, a compositional architecture is achieved through using abstractions for which we have a category - e.g. pure functions, monadic actions, pipes, etc.
  • Max
    Max over 7 years
    Alexander, could you kindly update this note when you're book is complete, so we could follow it. Cheers.
  • Alexander Granin
    Alexander Granin over 7 years
    Sure! For now I finished a half of the text, but it's a 1/3 of the overall work. So, keep your interest, this inspires me a lot!
  • Alexander Granin
    Alexander Granin almost 7 years
    Hi! I shared my book online (only first 5 chapters). See post on Reddit: reddit.com/r/haskell/comments/6ck72h/…
  • Max
    Max almost 7 years
    thanks for sharing and work!
  • jsk
    jsk over 6 years
    @semicon the difference for languages like Java is the existence of mature, well-tested and fully-automated tools for refactoring. Generally these tools have fantastic editor integration, and take away a huge amount of the tedious work associated with refactoring. Haskell gives us a brilliant type system with which to detect things that must be changed in a refactoring, but the tools to actually carry out that refactoring are (at the present moment) very limited, especially compared to what has already been available in the Java ecosystem for more than 10 years.
  • patriques
    patriques over 6 years
    Really looking forward to this!
  • Paul Johnson
    Paul Johnson about 6 years
    I agree that monad transformer stacks tend to be key architectural foundations, but I try very hard to keep IO out of them. Its not always possible, but if you think about what "and then" means in your monad you might discover that you really have a continuation or automaton somewhere at the bottom which can then be interpreted into IO by a "run" function.
  • McBear Holden
    McBear Holden about 6 years
    As @PaulJohnson has already pointed out, this Monad Transformer Stack approach seems in conflict with Michael Snoyman's ReaderT Design Pattern