I'm trying my hand at Euler Problem 4 in Haskell. It asks for that largest palindrome formed by multiplying two three-digit numbers. The problem was simple enough, and I thought my Haskell-fu was up to the task, but I'm getting a result that looks inconsistent to say the least.
Here's my palindrome detector (which was simplicity itself to code):
isPalindrome :: String -> Bool
isPalindrome [] = True
isPalindrome str = let str2 = reverse str
in (str2 == str)
From here it's a simple question of writing a function to detect when a product forms a palindrome (and possibly to subtract one from one of the multiplicands and recurse over a brute-force search if it doesn't). Here's my very simplified version of this, stripped down and returning an IO action for debugging:
findPal :: Integer -> Integer -> IO()
findPal 1 y = putStrLn "reached 1"
findPal x y = let pal = isPalindrome $ show mult
mult = x * y
in case pal of
true -> putStrLn $ "mult is " ++ (show mult)
false -> putStrLn "pal is false"
Here are two separate outputs in GHCi:
*Main> isPalindrome $ show (999*999)
False
*Main> findPal 999 999
mult is 998001
In other words, the call to isPalindrome is always evaluating to true in findPal's case statement, even when it should be false.
What am I not seeing here?
I think you need to capitalize "True" and "False." I don't have a Haskell interpreter handy but you are probably just declaring a new variable "true" to be equal to "pal"
Could it be that in findPal, you should write True
and False
instead of true
and false
?
EDIT: Ok, thoroughly beaten by the early bird here...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With