An interesting programming puzzle appeard in the Blogosphere: To describe every integer from 1 to 100 as a calculation involving only and exactly four fours, and standard operations. There are solutions in C# (code) and in python (code), so I tried to do mine in Haskell.
This seems to be meant for Haskell. The Type system makes the program really great to read. Functional programming allows me to conveniently create all possible associations of four operands with three binary operations. (I found five. Why are the other two sources using four?) And, in this program particular, the use of the list monad to quickly generate a list of all possible combination is really a programming-time-saver.
The program is not too slow either (IBM Thinkpad T41p with Intel M 1700MHz):
$ time ./fourfours >/dev/null real 0m0.917s user 0m0.852s sys 0m0.040s
And it could probably be sped up by using some kind of hashing or similar stuffs. Note that the program has only 73 mostly quite short lines, while the python code has 119 and the C# code has 138 of relatively long lines (comments and empty lines not counted). I think this is impressive (unless you have worked with haskell a bit, then you are used to these kind of results). Comments welcome!
FourFours in Common Lisp
I came across the FourFours problem recently. Stated succinctly, it asks:
what are the ways to calculate each of the integers from 1 to 100 with
formulas which use the digit four exactly four times? (No digits other
than four can be used at all.)
I decided to take a shot at the problem in Haskell as well.
I don't know how to properly include code in comments on your blog, so here's a link which should work as long as my computer is on (which is usually always the case).
Very nice. I had :x: as infix constructors once, but had some problems them. I also like the use of monads to handle evaluation errors, something I considered, but did not do (I yet have to learn more about Monads).
I especially like how you do not specify a monad for eval, and it just falls into place when it is used in the list comprehension.
If I understand your code correctly, you're using exponentiation as one of your operators. (I don't really know Haskell, though.) In both Python and C#, the '^' operator is bitwise xor, not exponentiation.
Neither is needed, though. I was able to get all 100 numbers using just addition, subtraction, multiplication, and division. (This was in Common Lisp, which does ratios for integer division; perhaps C#'s and Python's division operators don't work in the same way. OTOH, I still got all the numbers when using truncate instead of /, so who knows?)
Comment about the list monad thing: I agree that it is a nice example of using the list monad, but I find in this case it is not really necessary to go the monad way when list comprehension offers the same: