【问题标题】:Haskell list comprehension (print sqrt for element of list)Haskell 列表理解(为列表元素打印 sqrt)
【发布时间】:2015-03-17 12:57:25
【问题描述】:

我有 GHCi,版本 7.8.3。我想计算可以被 10 整除的 sqrt 项的总和。

如果我写[ x | x <- [10..100], x `mod` 10 == 0]sum [sqrt x | x <- [10..100]] 是正确的。

但是如果我在显示错误的时候写sum [ sqrt x | x <- [10..100], x `mod` 10 == 0]

'<interactive>:39:1:
    No instance for (Show t0) arising from a use of ‘print’
    The type variable ‘t0’ is ambiguous
    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 a stmt of an interactive GHCi command: print it'

如何改命令,程序是否正确?

【问题讨论】:

    标签: list haskell list-comprehension


    【解决方案1】:

    问题在于,当你使用mod时,号码的类型必须是Integral a =&gt; a,而当你使用sqrt时,号码的类型必须是Floating a =&gt; a。 GHC 知道没有适合这两个约束的类型,尽管因为您在 GHCi 中执行它,所以无论出于何种原因,错误消息大多是无用的。错误消息是这样的,因为 GHCi 使用print,它调用show,并且由于某种原因,这是第一个被检查的约束。由于没有具有约束ShowIntegralFloating 的类型,因此它不进行类型检查。

    您的另外两个示例类型检查,因为它们只使用modsqrt 之一。在应用sqrt 之前,您可以使用fromIntegral 将两者结合起来使用:

    sum [sqrt $ fromIntegral x | x <- [10..100], x `mod` 10 == 0]
    

    【讨论】:

    • 让我想知道是否有任何类型具有IntegralFloat 的合理实例。我注意到类似f x = sqrt (mod x 10) 的东西很高兴地对定义f :: (Floating a, Integral a) =&gt; a -&gt; a 类型的函数进行类型检查——但我不知道任何适合该法案的a 类型。 :-}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多