我试图使这个函数工作:
save dist dur speed
|modulus<dur = True
|otherwise = False
where modulus = mod (dist/(speed/3.6)) (2*dur)
根据我使用的类型声明,我会遇到不同的错误。我打算在 Ints 上使用该功能。
我试过写作
save :: Int->Int->Int->Bool
并通过
save :: Int -> Int -> Int -> Bool
save dist dur speed
|modulus<dur = True
|otherwise = False
where ndist=fromIntegral dist
ndur=fromIntegral dur
nspeed=fromIntegral nspeed
modulus = mod (ndist/(nspeed/3.6)) (2*ndur)
通过这次尝试,我得到错误:
* No instance for (Fractional Int) arising from a use of `/'
* In the second argument of `(/)', namely `(nspeed / 3.6)'
In the first argument of `mod', namely `(ndist / (nspeed / 3.6))'
In the expression: mod (ndist / (nspeed / 3.6)) (2 * ndur)
|
8 | modulus = mod (ndist/(nspeed/3.6)) (2*ndur)
| ^^^^^^^^^^
Failed, no modules loaded.
我希望你能告诉我如何使这个函数工作,也许如何以正常的方式编写它。
Haskell 的mod
只适用于积分类型,/
只适用于分数类型。 没有类型是两者兼而有之,因此您需要明确要转换的位置。 一种选择是:
save :: Double -> Integer -> Double -> Bool
save dist dur speed
|modulus<dur = True
|otherwise = False
where modulus = mod (round (dist/(speed/3.6))) (2*dur)
如果您希望所有输入的类型相同,则可以插入其他转化。