假设我有以下Haskell类型描述:
为什么在我尝试用ghc运行这个程序时会出现以下信息:
通过运行
divide_by_hundred :: Integer -> IO()
divide_by_hundred n = print(n/100)
为什么在我尝试用ghc运行这个程序时会出现以下信息:
No instance for (Fractional Integer) arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Integer)
In the first argument of `print', namely `(n / 100)'
In the expression: print (n / 100)
In an equation for `divide_by_hundred':
divide_by_hundred n = print (n / 100)
通过运行
:t (/)
,我得到了以下结果:(/) :: Fractional a => a -> a -> a
我认为这表明(/)可以接受任何可以表示为分数的数字(我认为这应该包括整数,但我不确定如何验证),只要/
的两个输入类型相同。
显然这是不准确的。为什么呢?我该如何编写一个简单的函数来将整数除以100?
IO
单子中进行的习惯。除了其他优点外,这使返回类型显式化(print
会隐藏类型),从而提供更多控制权。此外,请注意camelCase是Haskeller们的惯例。因此,您应该确实将divideByHundred :: Integer -> Integer
或者divideByHundred :: (Fractional f) => Integer -> f
。 - leftaroundabout