Haskell模类似于JavaScript(考虑符号并适用于非整数)

dfty9e19  于 9个月前  发布在  Java
关注(0)|答案(1)|浏览(86)

在JavaScript中:

console.log(13 % 5);
// Expected output: 3

console.log(-13 % 5);
// Expected output: -3

我在Haskell也需要同样的东西。我做

:{
modulo :: Double -> Int -> Double
modulo a p = 
    let p' = fromIntegral p
    in
    if a > 0 
        then a - fromIntegral(p * floor(a/p'))  
        else a - fromIntegral(p * ceiling(a/p'))
:}

这似乎是有效的(至少我发现与JavaScript的结果相同)。有更好的办法吗?
rem相反,它应该适用于Doublea

ghci> modulo (-13.5) 5
-3.5
8ftvxx2r

8ftvxx2r1#

已经存在,为**rem :: Integral a => a -> a -> a**:

ghci> 13 `rem` 5
3
ghci> (-13) `rem` 5
-3

Haskell有两对关于除法和取模的函数:divmod,它们向负无穷大截断;以及quotrem,它们向零截断。
RealFrac类型:

fracRem :: (RealFrac a, Integral b) => a -> b -> a
fracRem x y = x - fromIntegral (y * (truncate x `quot` y))

相关问题