INCLUDE_DATA

Starting with Haskell

Recently I’ve taken it upon myself to learn Haskell. I haven’t had much time lately to work on programming projects at home, so I felt it was time to start something again. I decided to learn Haskell since I’ve never truly learnt a functional programming language. I’ve tried some functional programming some during a couple of University courses, but I’ve never got to the point where I truly understood it and naturally thought of functional solution to problems.

To help with the learning I bought the Real World Haskell book, and I’ve decided to do most of the exercises in the book and post my solutions to them here.

The first chapter didn’t have any proper programming questions of interest, so I’m skipping those and going straight to chapter two instead where we’re asked to create a lastButOne function that retrieves the penultimate element in a list.

After a bit of thinking I came up with the following solution:

lastButOne xs = if null (tail (tail xs))
    then head xs
    else lastButOne (tail xs)

It isn’t the most elegant solution, since it doesn’t work for empty lists, but it gets the job done. Enough to make me happy at this stage of Haskell-learning. What it does is check if the list is empty if two elements are removed; if it is then the first element in the list is the penultimate, if not it removes the first element and tries again.

Now I’m off to take on the third chapter, about data types and some other stuff.

Leave a Comment