2017-07-25 68 views
-3

我想在Haskell中編寫一個函數來整數。這是我的代碼:在Haskell中分類時輸入錯誤

div :: Int -> Int -> Double 
div a b =a/b 

然而,當我嘗試complie它,我總是得到錯誤:

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. 
+1

這裏有一個答案https://stackoverflow.com/questions/35950600/why-it-is-impossible -to-除以整數數在-Haskell中 –

回答

2

您需要的Int S使用realToFrac先轉換,例如。重命名divmyDiv避免與前奏的衝突,節目

myDiv :: Int -> Int -> Double 
myDiv a b = realToFrac a/realToFrac b 

main = putStrLn $ show $ myDiv 5 2 

輸出

2.5