Haskell Christmas Tree


Below is my solution to one of the exercises created by the Functional Brighton group: draw a Christmas tree to the console, given the height of the tree as input. It demonstrates some of the Input and Output of Chapter 9 of Learn You A Haskell For Great Good.

In terms of tree visuals we are going for a fairly minimalist approach:

To model the tree, draw from two sets of integers. The first being the number of spaces preceding each row - simply beginning at height-1 and decrementing to 0 (the last row of the tree, ignoring the trunk)

The second set of integers represent the stars that make up the actual tree. The set consists of the odd numbers beginning from 1. These are generated using a list comprehension:

Now we simply zip these two sets together into a list of tuples:

And run them through a stringifyer, converting each tuple to a number of space characters followed by a number of stars characters:

And now to the whole point of the IO chapter, to display something! It's simple using mapM_ which maps putStrLn over all tree strings and sequences the resulting IO actions. We display the tree trunk at the same time:


The program does not check for invalid input, such as height 0

Full listing