为什么我因使用show error而得到(Show t0)的No实例?

时间:2012-10-23 19:05:15

标签: haskell

我坚持这个问题而且我对Haskell很新,我试图用以下代码完成第一个Euler问题:

main = putStrLn . show . sum $ [3,6..1000]:[5,10..1000]

这是错误的第一部分:

euler/1.hs:1:19:
    No instance for (Show t0) arising from a use of `show'
    The type variable `t0' is ambiguous
    Possible fix: add a type signature that fixes these type variable(s)
    Note: there are several potential instances:
      instance Show Double -- Defined in `GHC.Float'
      instance Show Float -- Defined in `GHC.Float'
      instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
        -- Defined in `GHC.Real'
      ...plus 23 others
    In the first argument of `(.)', namely `show'
    In the second argument of `(.)', namely `show . sum'
    In the expression: putStrLn . show . sum

2 个答案:

答案 0 :(得分:6)

您期望[3,6..1000]:[5,10..1000]做什么? x : xs将对象准备到对象列表。这两个参数都是整数列表。您想要++代替(连接)。

需要说明的是,无论您期望:做什么,您的方法都是正确的。如果你想自己解决这个问题,我不会对此进行扩展。

答案 1 :(得分:4)

不幸的是,您收到的错误消息是错过了该问题。在ghci 7.4.2中加载它会提供更多有用的错误消息:

No instance for (Num [t0])
  arising from a use of `sum'
Possible fix: add an instance declaration for (Num [t0])
In the second argument of `(.)', namely `sum'
In the second argument of `(.)', namely `show . sum'
In the expression: putStrLn . show . sum

No instance for (Enum [t0])
  arising from the arithmetic sequence `5, 10 .. 1000'
Possible fix: add an instance declaration for (Enum [t0])
In the second argument of `(:)', namely `[5, 10 .. 1000]'
In the second argument of `($)', namely
  `[3, 6 .. 1000] : [5, 10 .. 1000]'
In the expression:
  putStrLn . show . sum $ [3, 6 .. 1000] : [5, 10 .. 1000]

这似乎暗示问题出现在[3, 6 .. 1000] : [5, 10 .. 1000]表达式中,实际上是因为:的类型为a -> [a] -> [a]x:xs只是添加了元素{{ 1}}到列表x的开头。在xs 您正尝试将[3, 6 .. 1000] : [5, 10 .. 1000]作为元素添加到[3, 6 .. 1000],但haskell中的列表必须包含相同类型的元素(它们是同类的),因此无效。这是因为[5, 10 .. 1000]的类型为[3, 6 .. 1000],而[Int]的元素的类型为[5, 10 .. 1000]

我认为您要找的是Int,其类型为++,而[a] -> [a] -> [a]是列表xs ++ ys和列表{{1}的串联}:

xs