在Haskell中进行偏差时出现类型错误
我正在尝试用Haskell编写一个函数,将其转换为整数。这是我的密码:在Haskell中进行偏差时出现类型错误,haskell,type-conversion,Haskell,Type Conversion,我正在尝试用Haskell编写一个函数,将其转换为整数。这是我的密码: div :: Int -> Int -> Double div a b =a/b 然而,当我尝试编译它时,我总是得到错误: baby.hs:20:10: Couldn't match expected type ‘Double’ with actual type ‘Int’ In the first argument of ‘(/)’, namely ‘a’ In the expression: a
div :: Int -> Int -> Double
div a b =a/b
然而,当我尝试编译它时,我总是得到错误:
baby.hs:20:10:
Couldn't match expected type ‘Double’ with actual type ‘Int’
In the first argument of ‘(/)’, namely ‘a’
In the expression: a / b
baby.hs:20:12:
Couldn't match expected type ‘Double’ with actual type ‘Int’
In the second argument of ‘(/)’, namely ‘b’
In the expression: a / b
Failed, modules loaded: none.
您需要首先转换
Int
s,例如使用realToFrac
。将div
重命名为myDiv
以避免与前奏曲冲突,程序
myDiv :: Int -> Int -> Double
myDiv a b = realToFrac a / realToFrac b
main = putStrLn $ show $ myDiv 5 2
输出
2.5
这里有一个答案