具有不同参数的Haskell类型签名

Haskell type signatures with varying parameters

Project Euler_4:回文数字的读写方式相同。由两个两位数的乘积产生的最大回文是9009=91×99。找出两个3位数的乘积所产生的最大回文。

此解决方案有效:

1
2
3
4
5
6
7
8
9
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中会产生错误。

编辑:我试图插入一个类型签名,如下所示:

1
2
3
4
5
6
7
8
9
10
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

类约束与它们用=>约束的类型分离。