【问题标题】:Couldn't match type `Integer' with `Int'无法将类型“Integer”与“Int”匹配
【发布时间】:2015-03-20 15:51:44
【问题描述】:

我正在从事 Project Euler #41,这是我解决问题的一部分,我不知道如何绕过 Haskell 期待 [Int] 而不是 [Integer]。 Diglist 工作正常,但我将其包括在内以防错误以某种方式涉及它。

digList :: Integer -> [Integer]
digList n = digList' [] n where
        digList' xs n
                | n < 10        = n : xs
                | otherwise = digList' (lsd : xs) nxt
                where
                    lsd = n `mod` 10
                    nxt = n `div` 10

isNPandigital :: Integer -> Bool
isNPandigital n = isnp 1 (digList n) where --error on this line
    isnp i xs
        | i `elem` xs = isnp i $ delete i xs
        | i == length (digList n) = null xs
        | otherwise = False

错误是:

Couldn't match type `Integer' with `Int'
Expected type: [Int]
Actual type: [Integer]
In the return type of a call of `digList'
In the second argument of `isnp', namely `(digList n)'
In the expression: isnp 1 (digList n)

【问题讨论】:

    标签: haskell


    【解决方案1】:

    iisnp 的参数被推断为Int,因为您使用i `elem` xs,并且因为您使用i == length (digList n)。编译器认为i 应该是Int,因为您将它与length (digList n) 进行比较,后者总是返回Int,并且您使用的是i `elem` xs,因此xs 必须具有@ 类型987654332@,但是您将(digList n) 传递给xs,而digList n 的类型为[Integer],因此出现错误。

    【讨论】:

    • 有趣。在 Haskell 中处理这种类型差异的惯用方法是什么?我最终做了(toInteger . length . digList) xs,以便ghc 将i 的类型推断为Integer,但对toInteger 的额外调用似乎......对我来说很脏。
    • @wolf 你也可以使用genericLength :: Num i =&gt; [a] -&gt; i。它比length 稍慢,但可以返回任何类型的数字。
    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    相关资源
    最近更新 更多