Starting Haskell

I’ve started learning Haskell with the free online book Real World Haskell by Bryan O’Sullivan, Don Stewart, and John Goerzen. Exercise 2 in Chapter 2 Types and Functions asks for a function called lastbutone that returns the second last element in a collection of elements. Here’s a first version using conditional:

-- lastbutone-1.hs
-- Return the penultimate element, i.e. the element before the last element.
lastbutone :: [a] -> a
lastbutone xs =
    if (length xs) == 1 || null xs then
       head xs
    else
        head (drop ((length xs) - 2) xs)

And a sample interactive session:

ghci> :load lastbutone-1.hs 
[1 of 1] Compiling Main             ( lastbutone-1.hs, interpreted )
Ok, modules loaded: Main.
ghci> lastbutone [1, 2, 3, 4]
3
ghci> lastbutone [1, 2, 3]
2
ghci> lastbutone [1, 2]
1
ghci> lastbutone [1]
1
ghci> lastbutone []
*** Exception: Prelude.head: empty list

Here’s another version without conditional and using only head, tail, and reverse:

-- lastbutone-2.hs
-- Return the penultimate element, i.e. the element before the last element.
lastbutone :: [a] -> a
lastbutone xs =
    head (tail (reverse xs))

And a sample interactive session:

ghci> :load lastbutone-2.hs 
[1 of 1] Compiling Main             ( lastbutone-2.hs, interpreted )
Ok, modules loaded: Main.
ghci> lastbutone [1, 2, 3, 4]
3
ghci> lastbutone [1, 2, 3]
2
ghci> lastbutone [1, 2]
1
ghci> lastbutone [1]
*** Exception: Prelude.head: empty list
ghci> lastbutone []
*** Exception: Prelude.tail: empty list
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: