Coding and stuff

Saturday, February 19, 2011

Learning Haskell

As an always curious programmer, I want to learn interesting programming languages and new paradigms. Haskell is one of the languages I think would be interesting to learn. It is a purely funtional language, giving me the opportunity to learn a new paradigm - functional programming.

My earlier attempts at learning this language has not succeeded, mainly because of my short attention span and general lack of patience. I will now make a new attempt, and document the learning process in this blog. I hope that blogging will be the extra push needed to stay focused. It will also hopefully be of use for other programmers wanting to learn Haskell.

So, lets start with the traditional first program in a new language - "Hello, World!":
main=putStrLn "Hello, World!"

There are several compilers for Haskell. I choose to use the Glasgow Haskell Compiler. To compile this code (stored in the file hello.hs), I used the following command line:
ghc --make hello.hs

This will, in UNIX-like systems, create an executable file hello, which can be run simply by entering:
./hello

As expected, we get the following output:
Hello, World!
So, I managed to write, compile and run a program that prints one line of text on standard output. Not very interesting. What is more interesting is how this single line of source code made the program produce this output. In an imperative programming language that is quite simple - some boilerplate code, combined with a call to a function printing its argument.

In Haskell, it is a little more complicated. Functions can't have side effects, like printing something, and everything happens inside a function called main. In this case, main calls another function (putStrLn), accepting a string as its only argument. Even though the name putStrLn suggests it will write a string to somewhere, it doesn't actually do that. It only returns the action of writing the string. This action is a special value telling Haskell to perform it, if it is returned by main.

There are other actions than just printing a string. We can read from a file or standard input. Actions can also be combined, building up a sequence of IO actions. More about that later.

Thursday, May 3, 2007

First blog post

This is the first post in my blog about coding (and stuff). More interesting content wil soon appear.