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
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 =>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.