Find the Kth Element of a List
№3 · 99 Picat ProblemselementAt([X|_], 1) = X.
elementAt([_|Xs], K) = elementAt(Xs, K-1), K > 1.
Explanation
This function finds the element at position K in a list (using 1-based indexing).
Base case (line 1):
elementAt([X|_], 1) = X.
- Pattern matches when
K = 1(first position) - Returns the head of the list
X - The tail is ignored with
_since we found our element
Recursive case (line 2):
elementAt([_|Xs], K) = elementAt(Xs, K-1), K > 1.
- Uses the same
[Head|Tail]destructuring as Problem 1 - Ignores the head with
_and recursively processes the tail - Decrements
Kby 1 with each recursive call - Guard condition:
, K > 1restricts this clause to only match when K is greater than 1
Complete Example
Here's the full runnable code:
main =>
go_03.
go_03 =>
A = [5,4,3,2,1],
B = elementAt(A, 2),
println(B).
elementAt([X|_], 1) = X.
elementAt([_|Xs], K) = elementAt(Xs, K-1), K > 1.
How it works:
elementAt(A, 2)calls the function with two parameters: the list and the index- Picat uses 1-based indexing (position 1 is the first element, not position 0)
println(B)outputs4(the element at position 2)
Example Execution
With A = [5,4,3,2,1] and K = 2:
elementAt([5,4,3,2,1], 2)
→ elementAt([4,3,2,1], 1) (ignore 5, decrement K)
→ 4 (K = 1, return head)
The function strips off elements while decrementing K until K reaches 1, then returns the current head.
Takeaways
- Multiple parameters: Functions can take multiple arguments separated by commas
- Guard conditions:
, K > 1after the function body restricts when a clause can match - Counting down: Instead of counting up from 0, we count down from K to 1 - when K reaches 1, we've arrived at our target position