How to check if a number is palindrome in Clean

116 views Asked by At

I am solving this homework of clean programming language; The problem is we have a number of five digits and we want to check whether it's an odd palindrome or not. I am stuck at the stage of dividing the number to five separate digits and perform a comparison with the original number, for the palindrome check. With Clean I can't loop over the number and check if it remains the same from the both sides, so I am looking for an alternative solution (Some mathematical operations).

Code block:

isOddPalindrome :: Int -> Bool
isOddPalindrome a
| isFive a <> 5 = abort("The number should be exactly five digits...")
| (/*==> Here should be the palindrome check <==*/) && (a rem 2 <> 0) = True
| otherwise = False

isFive :: Int -> Int
isFive n
| n / 10 == 0 = 1
= 1 + isFive(n / 10)

My idea is to take the number, append it's digits one by one to an empty list, then perform the reverse method on the list and check if it's the same number or not (Palindrome)

2

There are 2 answers

1
Khalil On BEST ANSWER

After hours of trying to figure out how to recursively add the digits of our number to an empty list, I did the following:

sepDigits :: Int [Int] -> [Int]
sepDigits n x = sepDigits (n/10) [n rem 10 : x]

Now I can easily check whether the reverse is equal to the initial list :) then the number is palindrome.

1
Murtaza On

Your answer above doesn't have a stopping condition so it will result in stack overflow.

You could try this

numToList :: Int -> [Int]
numToList n
| n < 10 = [n]
= numToList (n/10) ++ [n rem 10]

Start = numToList 12345

and then like you mentioned in the answer, you can reverse it with the 'reverse' function and check if they are equal.