项目欧拉#4:回文数字两种方式相同。由两个2位数字的乘积制成的最大回文是9009 = 91×99。找到由两个3位数字的乘积制成的最大回文。
此解决方案有效:
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
我的问题是:你能否为where
子句中的函数分配类型签名,因为两者都有不同的参数排列([],[x],(x:xs))?坚持isPalindrome :: (Eq a) -> [a] -> Bool
会引发错误。
编辑:我试图像这样插入一个类型签名:
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
答案 0 :(得分:4)
你有一个错字。 [应]为
(Eq a) =>...
(箭头应以等号表示) - Michal Seweryn
类约束与它们用=>
约束的类型分开。