Recently I made some real progress on my Chinese Chess application which I will eventually put on Facebook. It is written in python and the rules of the game are pretty much complete and so I can run through a bunch of simulated games where each side makes a random move each time. I now have to design and create an interface for it so the game can actually be played. I am making a web app for it and going to use jQuery to help me out with it.
In learning jQuery and implementing my python I started to fall in love with functional programming. To generate the legal moves for a piece I used map and filter. These are functions which take a list and another function as their input. Then they go through the list applying the function to each element on the list. While this can be done with a loop its is much cleaner with these higher order functions. It took me a while to realize how passing a function as an argument to another function is amazing, it is like magic.
This came up again in jQuery. jQuery is a javascript library that makes doing useful things with JavaScript much easier. The amazing part is that it takes advantage of passing functions around as well. While I am still learning javascript I already am loving the functional parts of it.
All these functions prompted me to take the plunge into Haskell. Haskell is a pure, functional, and lazy programming language. It is a whole new way of thinking about programming for me, and so far I am in love with it. As an example let me show this piece of code I wrote which still blows my mind:
derivative f = (\x -> (f (x+dx) - (f x) ) / dx)
where dx = 0.0001
This is a function, that takes another function and returns the derivative of that function! What?! To show you what it does
Main> (derivative sin) 4
-0.6536057796480144
Main> cos 4
-0.6536436208636119
the inaccuracy is only because dx is set to be 0.0001 rather than an infinitesimal but that is all it takes to create calculus!
While I am certainly not proficient in Haskell yet I am having tons of fun reading through http://learnyouahaskell.com. After just the first few chapters my head exploded a few times but I was able to solve the first 10 project euler problems with Haskell.
The only problem I have with learning functional programming is the frustration when first class functions are taken away from me. In my parallel computing class I have to write MPI programs in C or FORTRAN. I do not think MPI supports first class functions, but I keep wanting to pass functions to other functions! I will be posting more about my progress with my chess application and functional programming progress shortly. I feel I am progressing quite a bit as a programmer which feels nice.

0 comments:
Post a Comment