Saturday, May 19, 2012

[mcvmgtve] divMod versus quotRem

A reference table comparing the behavior of Haskell functions divMod and quotRem for negative arguments. divMod is considered more mathematically elegant because of its "floor" behavior, floor (x/y), in contrast to quotRem's "round toward zero" behavior, but quotRem works faster in hardware.

x y divMod x y quotRem x y
47 10 4 7 4 7
-47 10 -5 3 -4 -7
47 -10 -5 -3 -4 7
-47 -10 4 -7 4 -7
2 10 0 2 0 2
-2 10 -1 8 0 -2
2 -10 -1 -8 0 2
-2 -10 0 -2 0 -2
60 10 6 0 6 0
-60 10 -6 0 -6 0
60 -10 -6 0 -6 0
-60 -10 6 0 6 0

module Main where { import List(intersperse) ; funcs :: [Integer -> Integer -> (Integer, Integer)] ; funcs = [divMod, quotRem] ; callfunc :: Integer -> Integer -> (Integer -> Integer -> (Integer, Integer)) -> String ; callfunc a b f = tdstring "" "" ++ tdtuple (f a b) ; table1 :: Integer -> [String] ; table1 absolute = do { b <- [10, -10] ; a <- [absolute, negate absolute] ; return $ wrap "tr" "" $ td a ++ td b ++ concatMap (callfunc a b) funcs } ; empty_row :: String ; empty_row = wrap "tr" "" $ wrap "td" "" ""; wrap :: String -> String -> String -> String ; wrap x extra y = "<" ++ x ++ extra ++ ">" ++ y ++ "</" ++ x ++ ">\n" ; tdstring :: String -> String -> String ; tdstring extra = wrap "td" ( " align = \"right\"" ++ extra ) ; blackbg :: String ; blackbg = color "black" "white" ; whitebg :: String ; whitebg = color "white" "black" ; color :: String -> String -> String ; color background foreground = " style = \"background-color: " ++ background ++ " ; color: " ++ foreground ++ "\"" ; td :: Integer -> String ; td x = tdstring (if (x < 0) then blackbg else whitebg) $ show x ; tdtuple :: (Integer, Integer) -> String ; tdtuple (x, y) = td x ++ td y ; main :: IO () ; main = putStrLn $ wrap "table" " border = \"1\" cellpadding = \"5\"" $ header ++ (unlines $ concat $ intersperse (return empty_row) $ map table1 [47 , 2 , 60] ) ; header :: String ; header = wrap "tr" "" $ th center "x" ++ th center "y" ++ th "" "" ++ thcols "divMod x y" ++ th "" "" ++ thcols "quotRem x y"; thcols :: String -> String ; thcols = th (center ++ " colspan = \"2\"") ; th :: String -> String -> String ; th extra = wrap "th" extra ; center :: String ; center = " align = \"center\"" }

No comments :