Pascal's triangle in mit-scheme
Keep your concerns separated

One design principle that is vital to engineering good software is that of "separation of concerns".  In other words, each function should be concerned with doing one, and only one, thing.

If you step back and take a look at the pascal function, you will see it's trying to do two things at once:


Compute Pascal's triangle
Pretty-print the triangle


You can separate these concerns.

Let's start with the pascal function.  It should only compute the values in the triangle.  It should return a list of "rows", where a row is represented a list of numbers.

So we can use pascal to compute a list of lists of numbers.  Now we want to pretty-print this list.  We could do this all in one function (and there's nothing really wrong with that).  But if we're careful, we can make things more generic (and thus reusable).  We can compose pretty-printing the triangle into the following:


Formatting each row.  This involves taking a list of numbers and returning a string representation for that row.
Centering the rows.  Basically, padding each string with spaces.
Printing the rows.  Taking the strings and print them each on separate lines.


We can define functions format-row, center-lines, and print-lines to handle these tasks.  Now we can define a function pretty-print-pascal that combines these functions:

(define pretty-print-pascal (x)
  (print-lines (center-lines (map format-row (pascal x)))))