Friday, October 19, 2007

Haskell, not your usual programming language

I am learning Haskell, and these are the points I came up with that summarizes the shock with the language. I'm proficient in other strict, unpure functional languages.
  1. Haskell is truly lazy. If there wasn't a need to print anything to the terminal, then computation simply would not happen. In other words, computation is bootstrapped by a side-effect. This explains why the main() expression in Haskell is an IO () monad. Program won't run without being a monad.
  2. An expression with a monadic type simply means it's using call-by-value semantics rather than the usual call-by-need in Haskell. It's analogous to the lazy keyword in O'Caml, which is used for call-by-need evaluation in a call-by-value language. It might be more comfortable for someone like me to start writing in the monad language of Haskell.
  3. There is no signaling mechanism in Haskell, but you can timeout a computation by running it on a separate thread, wait for the result or for the timeout on the current thread, then kill the computation thread if it runs out of time. This is how it is implemented in the System.Timeout module.
  4. Naturally, threads are also monad expressions. Even being a monad, thread won't run if it doesn't cause any side-effects. As a result, System.Timeout only works with expressions of a monadic type. Computation cannot be forced by simply lifting the expression to a monad using the return function.
  5. Haskell concurrency implementation only performs context switching when the program allocates from the heap. As a result, the following expressions do not time out (run forever):
    • length (repeat 1)
    • let xs = 1 : xs in length xs
    But the following do:
    • length [1..]
    • let xs = make_xs () where make_xs () = 1 : make_xs () in length xs
    Note that length xs does not terminate when xs is infinite. For brevity, the result of all the expressions above are printed using IO.putStr, which is the easiest way to force evaluation.
Post a Comment