Project Euler #4: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.
This solution works:
p004largestPalindrome :: Integer
p004largestPalindrome = largest [ a * b | a <- [100..999], b <- [100..999], isPalindrome $ show(a*b) ]
where
isPalindrome [] = True
isPalindrome [_] = True
isPalindrome (x:xs) = if x == last xs then isPalindrome (init xs) else False
largest [] = 0
largest [x] = x
largest (x:xs) = if x > head xs then largest (x:(tail xs)) else largest xs
My question is: can you assign type signatures to the functions in the where
clause, given that the both have different arrangements of parameters ([], [x], (x:xs))? Sticking in isPalindrome :: (Eq a) -> [a] -> Bool
throws an error.
Edit: I am trying to insert a type signature like so:
p004largestPalindrome :: Integer
p004largestPalindrome = largest [ a * b | a <- [100..999], b <- [100..999], isPalindrome $ show(a*b) ]
where
isPalindrome :: (Eq a) -> [a] -> Bool
isPalindrome [] = True
isPalindrome [_] = True
isPalindrome (x:xs) = if x == last xs then isPalindrome (init xs) else False
largest [] = 0
largest [x] = x
largest (x:xs) = if x > head xs then largest (x:(tail xs)) else largest xs
isPalindrome [] = True
, directly beneathwhere
– Mark Karavan(Eq a) =>...
(arrow should be made with equal sign) – Michal Sewerynlargest :: (Ord a) => [a] -> a
– Mark KaravanisPalindrome
has quadratic complexity when the simpler\x -> x == reverse x
has linear complexity. It does not really matters, since we have only short inputs, of course. – chi