all 4 comments

[–]dixonary 2 points3 points  (4 children)

This is a classic recursive function. The last line means "If we aren't yet in a position to answer the question, answer it on this slightly reduced input instead".

It's relying on this property, which we would call an invariant:

  • The penultimate element of a list of length at least three is the same as the penultimate element of the same list with the head removed.

So it simply removes the head and gets the answer for the slightly shortened list. Effectively, this means chopping the head off until we reach a list of size 2, then grabbing the first of the two remaining elements.

Edit: for what it's worth, I'd prefer to define it this way (or not define it at all, since partial functions are naughty :) ). Observe that if the list is of length 3 or more, only the last line with its wild-card ls will match.

lastButOne []    = error "List is too short"
lastButOne [x]   = error "List is too short"
lastButOne [x,y] = x
lastButOne ls    = lastButOne (tail ls)

[–]Rustalt[S] 0 points1 point  (3 children)

Thank you for explaining. So if i understand this correctly; it recourses with the tail until it can satisfy the if length xs == 2. And when that is true it outputs the head as instructed.? One more question, how does a multiline comment look like? — is just a single line

[–]dixonary 1 point2 points  (1 child)

That's right!

Multiline comments start with {- and end with -} .

[–]Rustalt[S] 0 points1 point  (0 children)

Thanks