Expressions vs. statements
If you are entirely new to programming please visit this Wikipedia entry about expressions. The first line contains a couple of terms wich will be our main vocabulary in this post.
Haskell is an expression based language. There are no statements in it, like in imperative ones. The following example illustrates the difference between an expression and a statement.
The error itself may look scary for a Haskell beginner, but fear not, you will develop an intuition for them pretty soon. Please note that I use the ">" character to indicate the prompt in GHCi.
Function application may be quite unusual for programmers coming from imperative languages: there are no parentheses, only spaces:
This allows us to spare a couple of parens. You can evaluate an expression before passing it to a function too:
In Haskell, expressions are evaluated only when needed, which is called non-strict, or lazy evaluation. The following snippet does not actually raise an error, contrary to the intuition.
In a strict language, we could not even store the list, because the evaluation of the error would happen before constructing the list. In Haskell, this is not the case. The error will only be raised if that value will be used. This requires an entirely different mindset to predict the performance characteristics of a program, but at the same time it allows us to glue our existing functions in a more modular fashion.
One of the most enlightening example of the modularity provided by lazy evaluation is the following: imagine that we need to get the smallest element in a list and we have no minimum function, but we have a function which can sort us the list. Now, if we sort the list in ascending order, the first element will be the smallest, but sorting an entire list to only get the first element is entirely wasteful. It is, in strict languages. But in non-strict ones, the sorting will only happen if needed: if we only need the first value, the sorting algorithm will only do the sorting until it can produce that one value we need: it will do no unnecessary work! If that did not blow your mind I suggest you to stand in the corner until you realize how awesome it is.
Defining values at top level is easy:
Ignoring the precise type of those expression, I think you can guess that x will be a number, y is a string, and z has the same value and type as z.
This is the exciting part! We will do actual computation here. The fact is, Haskell is an shamelessly concise language:
That's it! That line will add two numbers. Admittedly not too useful, but hey! We have to start somewhere. Using it is also as easy as ABC:
To venture deeper into the language we will have to befriend the types, but that is a story for an other day.