0
votes

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
1
Where exactly were you sticking that?jwodder
right before isPalindrome [] = True, directly beneath whereMark Karavan
You have a typo. Shod be (Eq a) =>... (arrow should be made with equal sign)Michal Seweryn
That worked. As did largest :: (Ord a) => [a] -> aMark Karavan
By the way, isPalindrome 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

1 Answers

4
votes

You have a typo. [Should] be (Eq a) =>... (arrow should be made with equal sign) – Michal Seweryn

Class constraints are separated from the types they constrain with =>.