得到错误“约束中的非类型变量参数:整数[a2]”

时间:2018-09-09 19:25:21

标签: haskell fold accumulator

我正在尝试使用以下代码来实现luhn算法:

luhn :: Int -> Bool
luhn x = (tail $ show (foldl (\acc x -> acc + (read x :: Int)) 0 (foldr doEncrypt [] $ zip [0..] (show x)))) == "0"
    where
        doEncrypt (i,y) acc = if not(even i)
            then head(((uncurry (+) . (`divMod` 10) . (*2)) y)) : acc
            else (head y) : acc

我现在遇到以下错误:

• Non type-variable argument in the constraint: Integral [a2]
  (Use FlexibleContexts to permit this)
• When checking the inferred type
    doEncrypt :: forall a1 a2.
                 (Integral a1, Integral [a2]) =>
                 (a1, [a2]) -> [a2] -> [a2]
  In an equation for ‘luhn’:
      luhn x
        = (tail
             $ show
                 (foldl
                    (\ acc x -> acc + (read x :: Int))
                    0
                    (foldr doEncrypt [] $ zip [0 .. ] (show x))))
            == "0"
        where
            doEncrypt (i, y) acc
              = if not (even i) then
                    head (((uncurry (+) . (`divMod` 10) . (* 2)) y)) : acc
                else
                    (head y) : acc

我看到该错误表明元组(a2)的第二部分是“非类型变量参数”。但是,Haskell似乎将此参数a2标识为Integral,而实际上却是Char。我如何才能告诉Haskell这是Char,并且Haskell不必再担心此变量的类型了?还是我不明白导致此错误的其他原因?

编辑: 当我移除(head y)并将其替换为y时,出现以下错误:

• Couldn't match type ‘Char’ with ‘[Char]’
  Expected type: [String]
    Actual type: [Char]
• In the third argument of ‘foldl’, namely
    ‘(foldr doEncrypt [] $ zip [0 .. ] (show x))’
  In the first argument of ‘show’, namely
    ‘(foldl
        (\ acc x -> acc + (read x :: Int))
        0
        (foldr doEncrypt [] $ zip [0 .. ] (show x)))’
  In the second argument of ‘($)’, namely
    ‘show
       (foldl
          (\ acc x -> acc + (read x :: Int))
          0
          (foldr doEncrypt [] $ zip [0 .. ] (show x)))’

1 个答案:

答案 0 :(得分:3)

我的解决方案在很多地方出了问题,但是下面的代码终于奏效了!

luhn :: Int -> Bool
luhn x = (tail $ show (foldl (\acc x -> acc + (digitToInt x)) 0 (foldr doEncrypt [] $ zip [0..] (show x)))) == "0"
    where
        doEncrypt (i,y) acc = if not(even i)
            then (head $ show(((uncurry (+) . (`divMod` 10) . (*2)) (digitToInt y)))) : acc
            else y : acc

非常感谢@WillemVanOnsem的指针,没有我可能无法解决这个问题!