Exercise 1-9
January 17, 2017
Sometimes it’s good to go back to basics. Here is Exercise 1-9 from The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie:
Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
Your task is to write a solution to Exercise 1-9. 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.
This is a state-machine:
Thus:
Well, for K&R we really ought to have a C program: like Jussi we have a state machine, but since gcc doesn’t seem to handle mutual tail recursion well (yet), I thought I was going to have to use gotos, but it can all be nicely done with two loops, one for each state. The first ‘continue’ isn’t necessary of course, but makes for a nice symmetry:
This is the assembler for that function (with gcc -03). As you can see, it’s pretty tight:
Here’s a Haskell version, written in a fairly direct style. I pipe the output of the program to `cat -e`, which indicates end-of-line with a dollar sign.
This is pretty much the same as the previous Haskell program, but golfed just a bit… :-) Fore!