InnerAlien

InnerAlien

Hardware|Software

19 Jan 2026

Find the Last Element of a List

№1 · 99 Picat Problems
myLast([X]) = X.
myLast([_|Xs]) = myLast(Xs).

Explanation

This function finds the last element of a list using recursive pattern matching.

Base case (line 1):

myLast([X]) = X.
  • Pattern matches a list with exactly one element [X]
  • Returns that element directly
  • This is where recursion stops

Recursive case (line 2):

myLast([_|Xs]) = myLast(Xs).
  • Pattern matches a list with at least one element using the "cons" notation [Head|Tail]
  • _ (underscore) ignores the head element - we don't care about it
  • Xs captures the tail (rest of the list)
  • Recursively calls myLast on the tail

Complete Example

Here's the full runnable code:

main =>
  go_01.

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

myLast([X]) = X.
myLast([_|Xs]) = myLast(Xs).

How it works:

  • main => is the entry point - Picat starts execution here
  • go_01. calls the go_01 predicate (period ends the statement)
  • A = [1,2,3,4,5] creates a list and assigns it to variable A
  • B = myLast(A) calls the function and assigns the result to B
  • println(B) prints the value (outputs 5)

Example Execution

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

myLast([1,2,3,4,5])
→ myLast([2,3,4,5])    (ignore 1)
→ myLast([3,4,5])      (ignore 2)
→ myLast([4,5])        (ignore 3)
→ myLast([5])          (ignore 4)
→ 5                    (base case: list has one element)

Each recursive call strips off the head until only one element remains, which is the last element.

Takeaways

  1. Pattern Matching: Different clauses match different list structures
  2. Recursion: Function calls itself with a smaller problem
  3. Underscore (_): Anonymous variable for values we don't need
  4. List Destructuring: [Head|Tail] syntax splits a list into first element and rest