Sunday, January 29, 2012

Haskell for Engineers - Unicode

The Glasgow Haskell Compiler supports Unicode variable names, which I find dramatically simplifies geometric and numerical code. To enable this extension, just include the following pragma before the module line in your source file:
{-# LANGUAGE UnicodeSyntax #-}
... then you are good to go! Of course, you still need a good way to enter Unicode symbols, so you should consult Wikipedia's great article on unicode input.

There is one catch, namely that the first character of all variables cannot be upper-case and that includes Unicode characters like Δ. The only way to get around this is to prefix it with some unintrusive character like _ or 'This also means that you should use lower-case theta, lower-case phi, lower-case psi, and so on.

I've provided some examples to whet your appetite for greek variables:
spherical (x, y, z) = (r, θ, φ)
    where r = sqrt $ x^2 + y^2
          θ = acos $ z / r
          φ = atan2 y x

π = pi

α = δω / δt
However, always keep in mind that Unicode makes it harder for other people to read and edit your source code, so don't go crazy.

No comments:

Post a Comment

Post a Comment