Form Letters

November 30, 2010

Welcome back, Jane!
We hope that you and all the members
of the Public family are constantly
reminding your neighbors there
on Maple Street to shop with us.
As usual, we will ship your order to
Ms. Jane Q. Public
600 Maple Street
Your Town, Iowa 12345

Everybody hates form letters. But they are part of the computing universe, and today’s exercise asks you to print them. Input to the form letter generator comes in two parts. First, there is a schema that defines the letter to be written. Here is the schema for the letter shown above:

Welcome back, $1!
We hope that you and all the members
of the $0 family are constantly
reminding your neighbors there
on $5 to shop with us.
As usual, we will ship your order to
$3 $1 $2. $0
$4 $5
$6, $7 $8

Variable text is identified as $n, where n is the field number from a database; although it’s not shown above, n can be larger than 9, extending right-ward until a non-digit is encountered. Also not shown above is the construct $$, which prints a literal dollar sign.

The data comes from a comma-separated values file, of the type we have previously encountered. In this case, records have nine fields: last name, first name, middle initial, title, street number, street name, city, state, and zip code. Here is a sample two-record data file:

Your task is to write a program that takes a schema and a data file and writes a series of form letters. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

OK, both mine and Chris’ have the same two issues in that they don’t work with > 10 elements and the $$ doesn’t work. This one should work (it’s uglier, but works as is often the case). It works backwards down the list so that $10 will be subbed out before $1 and it will leave a “$$” alone. At the end it changes the “$$” to a single “$”.

A bit longer than everyone else’s. My answer can deal with arbitrarily many elements, but handles only the subcase
of the $$ problem where no other $n remain after a $$ in a line of the schema.
I’ve included the imports, hashbang line, and the test at the end (copy-pasted schema and data from first page):

I came up with the following version, which can handle many elements but still fails when the schema contains “invalid” markup such as $$$$1 where the amount of $s is unbalanced.
I also used some map/lambda foo to make it more interesting :)