Question

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.

Was it helpful?

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)]

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top