I like programming.
Or at least I tend to think that I do.
Over the summer, I decided that I should learn Haskell. I hadn’t written code in a functional programming paradigm before, so I thought it would be a great escapade. And it has been amazing so far. Well that, and a bit different. Why? Well, there’s the functional aspect of the language. You can find tons of articles which comment upon how functional paradigm is different from objective, imperative, declarative and procedural paradigms, yada yada. This isn’t about that. This is more about the purity of the language.
I don’t think there are many programming languages that are as resolute as Haskell when it comes to purity. Depending on what kind of programmer you are, that might be either pleasant or annoying. The consequences, however, are profound and valuable.
What is a pure function? To put it simply, a pure function’s output is only dependant on its input values. This dependance on arguments can give a strong hint of what a pure function does: one only has to read a function’s name and its type signature. Let’s look at
not for example:
So even if we don’t know the name of this function, its signature alone limits the possible valid behaviors it can exhibit:
- Ignore its arguments and always return either
- Return its arguments unmodified.
- Negate its arguments.
And a list of stuff it cannot do: talk to the network, File I/O etc.
Purity makes the job of understanding code easier. The behavior of a pure function is not dependant on any global variable, or the contents of a certain database. It is by choice modular, and hence well-defined and self contained.
Haskell also makes working with impure code a bit easier (!). Haskell encourages a style of programming in which we separate code that must have side effects from code that doesn’t need side effects. In this style, impure code tends to be simple, with the “heavy lifting” done in the pure part.
A lot of risk in software lies in talking to the external beings (not humans!). It could be as simple as copying bad data, or as mind-numbing as injecting malicious patterns. Since Haskell’s type system is always aware and encourages to use a more secure programming style, it becomes easier to pinpoint the parts of our code which might have side-effects. This reduces the so called “attack surface”.
So far, Haskell has been rewarding in its own unique way. But there’s so much more to learn, and this is just the beginning.