InnerAlien

InnerAlien

Hardware|Software

01 Feb 2026

Find Out Whether a List is a Palindrome

№6 · 99 Picat Problems
isPalindrome(L) => L = myReverse(L).

Explanation

A palindrome is a sequence that reads the same forward and backward. Examples: [1,2,3,2,1], [a,b,c,b,a], or even [x].

The logic is simple: a list is a palindrome if it equals its reverse.

The predicate clause:

isPalindrome(L) => L = myReverse(L).
  • The predicate succeeds when L unifies with its reversed version
  • If they match, it's a palindrome; if not, unification fails and the predicate fails

This uses the myReverse/1 function from Problem 5. We could also use Picat's built-in reverse/1.

Complete Example

Here's the full runnable code:

main =>
  go_06.

go_06 =>
  A = [1,2,3,2,1],
  B = [1,2,3,4,5],
  if isPalindrome(A) then
    println("true")
  else
    println("false")
  end,
  if isPalindrome(B) then
    println("true")
  else
    println("false")
  end.

isPalindrome(L) => L = myReverse(L).

myReverse(L) = myReverse(L, []).
myReverse([], R) = R.
myReverse([X|Xs], R) = myReverse(Xs, [X|R]).

How it works:

  • A = [1,2,3,2,1] is tested - it's a palindrome, so prints true
  • B = [1,2,3,4,5] is tested - not a palindrome, so prints false
  • isPalindrome(L) is a predicate (succeeds or fails), so we use it in an if-then-else statement
  • The predicate succeeds when the list equals its reverse

Example Execution

Testing [1,2,3,2,1]:

isPalindrome([1,2,3,2,1])
→ [1,2,3,2,1] = myReverse([1,2,3,2,1])    (check if list equals its reverse)
→ [1,2,3,2,1] = [1,2,3,2,1]               (myReverse returns [1,2,3,2,1])
→ true                                    (unification succeeds - they match!)

Testing [1,2,3,4,5]:

isPalindrome([1,2,3,4,5])
→ [1,2,3,4,5] = myReverse([1,2,3,4,5])    (check if list equals its reverse)
→ [1,2,3,4,5] = [5,4,3,2,1]               (myReverse returns [5,4,3,2,1])
→ false                                   (unification fails - they don't match)

Takeaways

  1. Predicates vs functions: Unlike previous problems where we computed values using functions (= expression), isPalindrome is a predicate that succeeds or fails. In Picat, predicates use => and work with unification. See the Predicates and Functions chapter in the official Picat guide for more details.

  2. Unification for equality: The = operator does unification, which checks if two terms can be made identical. When both sides are ground (fully instantiated), it acts like equality testing. Learn more in the Equality Testing, Unification, and Term Comparison section of the Picat guide.