首页 > 解决方案 > 传递输出小数作为参数的函数时出错,但直接传递浮点数时出错

问题描述

我正在尝试编写一个接受数字和列表的函数,如果列表中的最大数字和输入数字可整除,则返回结果加 1,但如果不可整除则返回结果的上限

我的代码如下:

maxDiv n xs 
   | maximum xs `mod` n == 0 = ((maximum xs `div` n) + 1)
   | otherwise = ceiling (1.8)

问题是当我将 1.8 替换为

((maximum xs) / n)

我收到一个错误,我将在下面发布。我试过将它放入一个单独的命名函数中,以及将它与天花板部分一起放入一个单独的函数中,例如

helper n xs = ceiling ((maximum xs) / n)
length' n xs | maximum xs `mod` n == 0 = ((maximum xs `div` n) + 1) | otherwise = helper n xs

但我仍然得到同样的错误。

• Ambiguous type variable ‘a0’ arising from a use of ‘print’
  prevents the constraint ‘(Show a0)’ from being solved.
  Probable fix: use a type annotation to specify what ‘a0’ should be.
  These potential instances exist:
    instance (Show b, Show a) => Show (Either a b)
      -- Defined in ‘Data.Either’
    instance Show Ordering -- Defined in ‘GHC.Show’
    instance Show Integer -- Defined in ‘GHC.Show’
    ...plus 23 others
    ...plus 43 instances involving out-of-scope types
    (use -fprint-potential-instances to see them all)
• In a stmt of an interactive GHCi command: print it

我看过打字,它们似乎都是小数,我做错了什么/有什么办法解决这个问题?

标签: haskell

解决方案


你在这里混合了“ Integral”世界和“ Fractional”世界。实际上,div :: Integral a => a -> a -> aandmod :: Integral a => a -> a -> a使用的是类型Integral,而(/) :: Fractional a => a -> a -> a使用的是属于 typeclass 成员的类型的项目Fractional

虽然,严格来说,可以在 Haskell 中创建一个既是Integral,又是 的类型,但这Fractional两个世界并没有太多共同点。此外,无论如何我们都不需要。如果要计算 的上限a/b,可以使用 计算div (a+b-1) b。我们甚至可以div (a+b) b在这里使用,因为您想添加+1它是否可除:

maxDiv :: (Integral a, Foldable t) => a -> t a -> a
maxDiv n xs = div (maximum xs + n) n

推荐阅读