Wednesday, April 14, 2010

Just a thought or two on strictness

I've noticed that a lot of times when it comes to profiling programs in any language, that it is often surprising where the big cost centers are. Maybe it's just due to experience, but a lot of times I at least feel like I'm not as surprised in imperative languages when I recognize a cost center or my tool chain does. With functional languages, I'm often surprised that certain implementations of functions are as costly as they are, while others are not. This is even more true in "lazy" functional languages like Haskell.

When you're dealing with strict evaluation by default, you can basically just read the program top down and get a good idea for what happens when, and how data much a particular chunk of code ought to be using, and for the most part you'll get this right with experience.

With a language like Haskell, sometimes, all bets are off unless you know very well how a particular library of functionality is implemented. There's both strict and non-strict versions of Control.Monad.State for example. The non-strict version almost requires you to read the code, then think about how much stuff can be deferred to the last minute, and realize that those little deferred computations will have to be evaluated later. This can not only change the order of evaluation and thusly the data size of your program, but can also change the behavior a great deal.

Data.Map has operations within it for update that will be deferred (non-strictly evaluated) and some that are strict. It's important to read the documentation.

My advice to beginners is to try to understand strictness vs non-strictness (often called laziness) in Haskell as early as possible. It will give you great leverage to expressing some really beautiful solutions to problems, and save you from pulling all of your hair out or suffering any existential crises when trying to figure out why a program doesn't do what you thought.

All of that said, it's pretty easy for me to see why some people will decide that non-strict functional programming languages are not for them. It certainly takes a little mind bending to see the value in it if all you've ever done is imperative or strict functional programming, but I promise you the value is truly there. I also find that by challenging myself to learn how to think in these new paradigms I am simultaneously strengthening my understanding of the older paradigms a good deal more, so give it a shot and don't give up! There's help out there for you.

No comments:

Post a Comment