InnerAlien

InnerAlien

Hardware|Software

22 Jan 2026

Find the Second-to-Last Element of a List

№2 · 99 Picat Problems
secondLast([X,_]) = X.
secondLast([_|Xs]) = secondLast(Xs).

Explanation

This function finds the second-to-last (penultimate) element of a list using the same recursive strategy as Problem 1, but with a different base case.

Base case (line 1):

secondLast([X,_]) = X.
  • Pattern matches a list with exactly two elements [X,_]
  • Returns the first element X (which is the second-to-last of the original list)
  • The second element is ignored with _

Recursive case (line 2):

secondLast([_|Xs]) = secondLast(Xs).
  • Uses the same [Head|Tail] destructuring as Problem 1
  • Ignores the head and recursively processes the tail

Complete Example

Here's the full runnable code:

main =>
  go_02.

go_02 =>
  A = [1,2,3,4,5],
  B = secondLast(A),
  println(B).

secondLast([X,_]) = X.
secondLast([_|Xs]) = secondLast(Xs).

How it works:

  • main => calls go_02 to run this problem
  • A = [1,2,3,4,5] creates the test list
  • B = secondLast(A) calls the function
  • println(B) outputs 4 (the second-to-last element)

Example Execution

With A = [1,2,3,4,5]:

secondLast([1,2,3,4,5])
→ secondLast([2,3,4,5])    (ignore 1)
→ secondLast([3,4,5])      (ignore 2)
→ secondLast([4,5])        (matches [X,_] where X=4)
→ 4

The recursion stops when the list is reduced to exactly two elements, returning the first of those two.

Takeaways

The only difference from Problem 1 is the stopping condition: instead of [X] (one element), we use [X,_] (two elements). This pattern generalizes: to find the Nth-from-last element, your base case would match a list of N elements and return the appropriate one.