Here's a good trick reminiscent of the standard Fibonacci trick. We will build a lazy list; each member of the list will be a list of all trees with a given number of nodes. There is only one tree with no nodes, Empty , and this will serve as our base case. To build all the trees with nodes n , suppose we already know how to build trees with nodes 0 , 1 , 2 , ..., n-1 . Then we just do not deterministically select the pairing of those that sums with n-1 , and glue a Node on top.
In code:
import Control.Monad import Data.List sizes :: [[FormTree]] sizes = [Empty] : (map go . drop 1 . inits) sizes where go smaller = do (ls, rs) <- zip smaller (reverse smaller) liftM2 Node ls rs
Then we can simply define allPossibleTrees = concat sizes , if necessary. The first few entries:
*Main> mapM_ print (take 4 sizes) [Empty] [Node Empty Empty] [Node Empty (Node Empty Empty),Node (Node Empty Empty) Empty] [Node Empty (Node Empty (Node Empty Empty)),Node Empty (Node (Node Empty Empty) Empty),Node (Node Empty Empty) (Node Empty Empty),Node (Node Empty (Node Empty Empty)) Empty,Node (Node (Node Empty Empty) Empty) Empty]
We can quickly check the performance:
*Main> take 10 (map length sizes) [1,1,2,5,14,42,132,429,1430,4862]
... these are really the first ten Catalan numbers , so we probably got it right!