0

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)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Khalil
  • 33
  • 7

2 Answers2

1

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.

Murtaza
  • 11
  • 2
  • 1
    The stopping condition is the number of digits itself, so it will just append each digit to a "new" list, when the digits are completed the recursion will stop. There's no stack overflow. I like your approach to the problem anyways, thank you for sharing! – Khalil Mar 12 '22 at 16:16
0

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.

Khalil
  • 33
  • 7
  • 1
    You could also use `fromString (toString n)` to get a `[Char]` containing the digits of `n`, and check equality on the reverse. But that may not be the intention of the exercise. –  Mar 01 '22 at 15:19