Find the Last Element of a List
№1 · 99 Picat ProblemsmyLast([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 itXscaptures the tail (rest of the list)- Recursively calls
myLaston 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 herego_01.calls thego_01predicate (period ends the statement)A = [1,2,3,4,5]creates a list and assigns it to variableAB = myLast(A)calls the function and assigns the result toBprintln(B)prints the value (outputs5)
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
- Pattern Matching: Different clauses match different list structures
- Recursion: Function calls itself with a smaller problem
- Underscore (
_): Anonymous variable for values we don't need - List Destructuring:
[Head|Tail]syntax splits a list into first element and rest