【问题标题】:No instance for (RealFrac Int) arising from a use of ' ... '没有因使用“...”而产生的 (RealFrac Int) 实例
【发布时间】:2017-03-16 07:09:04
【问题描述】:

下面的程序应该检查输入 n 是否可以被 n 中的数字之和整除

module Harshad where

isHarshad :: Int -> Bool
isHarshad n = (mod n (sumDig n)) == 0)
 where 
  sumDig n 
   | (floor (n / 10) == 0) = n -- n consists of only one digit
   | otherwise = sumDig (floor (n / 10)) + floor (10*(n - floor (n / 10)))

我得到以下编译错误: * 没有使用 `sumDig' 产生的 (RealFrac Int) 实例

即使在尝试添加各种转换后,我仍然卡住了。

【问题讨论】:

  • sumDig 应该有什么类型?
  • 我想的一个 Int

标签: haskell types functional-programming


【解决方案1】:

完全删除小数,仅使用div 进行整数除法:

sumDig n = if n < 10 then n -- n consists of only one digit
           else sumDig (n `div` 10) + (n `mod` 10)

【讨论】:

  • 这个div函数,是floorceiling还是round?如何改变这种行为?
  • @SimonBaars 从链接的文档中,“整数除法被截断为负无穷
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多