Search code examples
haskellpalindrome

Palindromes in Haskell


I am working on Project Euler Problem 4, and need to find the palindrome of the product of 2 3 digit numbers, so I came up with:

palindrome = [ x*y | x <- [100..999], y <- [100..999], reverse [x*y] == [x*y]]

Why doesn't this work and how can I make it work? I suspect I need to somehow get the answer into a list so that it be reversed and checked if it is a palindrome.


Solution

  • This part

    reverse [x*y] == [x*y]
    

    is wrong. [x*y] is a list with a single element: the result of x*y. The reverse is the same list...

    What you want is the number with its digits reversed. You need a list with the digits of the number. A simple trick to do that is convert the number to its string representation (remember that type String = [Char]). To do this you can use show, instead of [ ]:

    palindrome = [ x*y | x <- [100..999], y <- [100..999], reverse (show (x*y)) == show (x*y)]