This autumn I had a first look at Haskell. I’ve been meaning to write a post about my initial thoughts on it for a while now. Here it is.

To learn about Haskell I started reading Learn you a Haskell for Great Good. I also started trying to solve programming puzzles on Project Euler.

I spent a lot of time fighting with Haskell’s compiler. But once I finally made the program run I got to experience the “Haskell correctness guarantee” which is that code that compiles have a very high chance of running with no errors. This also made it easier to do large code reorganizations since I would instantly know if something was wrong.

## “A prime example”

```
-- Recursively check if a number is a prime.
isPrime divisor numToCheck
| divisor > (squareRoot numToCheck) = True
| numToCheck `mod` divisor == 0 = False
| otherwise = isPrime (divisor + 1) numToCheck
where squareRoot x = fromIntegral $ floor $ sqrt (fromIntegral x)
-- An infinite list of primes!
primes = [x | x <- [2..], isPrime 2 x]
-- Will find and print the 10001'th prime number.
main = print $ primes !! 10001
```

In the code above you can see a infinite list of primes! It’s not that this can’t be expressed in any other programming languages. Rather it’s more that the language is capable of nicely expressing it.

Primes get progressively harder and harder to compute as the number grows. Thanks to the lazy nature of Haskell you can define infinite lists where the actual content is only computed at the point when you ask for the value. In the code above when I ask for the 10001’th prime number the code goes and evaluates numbers from 0 up to including the 10001 prime number. We could ask for a much higher prime number though that would take a long time to compute.

## Other thoughts

It was a bit of a challenge to figure out how to get started with Haskell. Some sources recommended using Stack others did not recommend it. Haskell’s package management system Cabal still puzzles me a bit. I ended up installing the Haskell Platform which provided a sensible starting point for me. It was nice to see that the Haskell Platform package was available through Ubuntu’s package management system.

- There are a lot of nifty built-in functions and keywords to remember.
- There are a lot of “acrobatic grammar” (syntactic sugar) to remember.
- An elegant code solution might be sitting right in front of you but if you don’t remember all the keywords, functions and syntax possibilities you’ll miss it.
- Compiler errors can be cryptic. Haskell infers types meaning that it can figure out whether or not you’re working with say a list of characters or some special number type. I found it’s easy to get tripped up by functions that accept or return unexpected data types.

All in all it was nice to learn a bit about Haskell. I hope to use it for a more substantial project in the future. But there’s a lot of interesting languages out there. I’ll have to see. :)