简体   繁体   中英

How to check if a number is palindrome in Clean

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM