Question: Consider the following function for finding the second-to-last element of a list:

```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x

```

This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)?

Answer: 
Exploiting `zip`:

```
\l -> fst . last $ zip l (tail l)

```

Also available in a pointless, obfuscated style:

```
fst . last . (zip <*> tail)

```

or even without parentheses (thanks to @melpomene):

```
fst . last . ap zip tail

```

Other variants:

```
last . ap (zipWith const) tail

```
Another solution:

```
myButLast [] = error "List is empty"
myButLast [x] = error "List is a singleton"
myButLast xs = last $ init xs

```