views:

561

answers:

2

I am working on Project Euler question 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.

+1  A: 

You do not want to apply the reverse function to a list that contains a single number. You need to apply the reverse function to the string representation of that number.

Try using the "show" function.

Also, if you have enough strength to avoid looking at it and ruining the entire purpose of Project Euler, you can look at this:

http://www.haskell.org/haskellwiki/Euler_problems

Greg
+6  A: 

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)]
Martinho Fernandes
btw: this code tells me the answer is 906609.
Martinho Fernandes
But I wanted to compute it! Thanks anyway
Jonno_FTW
Sorry if I ruined you the joy of running the code and looking at the result to find out the answer. Oh... that warm fuzzy feeling... It wasn't my intention :)
Martinho Fernandes