Strange list behavior

I study the basics of Haskell and try to solve simple Euler problems: find the largest palindrome of three-digit numbers (100.999). I wrote this code:

palindrome = maximum $ filter (\a -> reverse a == a) $
                                    map show [ x*y :: Int | x <- [100 .. 999],
                                                            y <- [x, x+1 .. 999]]

He gives the wrong answer = 99999, when I change it to x <- [307 .. 999], the answer is still incorrect: 94249 (all the palindromes, but not the largest), and finally, when I change it to x <- [308 .. 999],, he gives me the correct answer: 906609.

I really don’t understand this behavior: it seems that overflow and truncation are happening in the generated list. Can someone explain this wrong behavior to me? I do not want to answer the task: I know that my solution is not very effective. I just want you to explain this code behavior (list truncation or memory problems). Thank.

+4
source share
1 answer

The result filteris a list of values String, so it maximumcompares them lexicographically. First you need to convert the values ​​back to Int. A type signature ensures that it readreturns values ​​of the correct type.

palindrome :: Int
palindrome = maximum . map read . filter ...

Another approach is only to convert the value to Stringin the filter itself:

palindrome :: Int
palindrome = maximum $ filter (\a -> let sa = show a in reverse sa == sa) [ x*y | x <- [100..999], y <- [x..999]]
+9
source

Source: https://habr.com/ru/post/1666151/


All Articles