divRem by `-' performance

Roman Cheplyaka roma at ro-che.info
Wed Oct 17 17:17:28 CEST 2012


* Serge D. Mechveliani <mechvel at botik.ru> [2012-10-17 19:02:37+0400]
> People,
> consider the following contrived program for division with remainder:
> 
> ----------------------------------------------------------------
> qRem :: Int -> Int -> (Int, Int)
> qRem m n = if m < 0 || n <= 0 then  error "\nwrong arguments in qRem.\n"
>            else                     qRem' 0 m
>            where
>            qRem' q r = if r < n then (q, r)  else qRem' (succ q) (r - n)

You need to force evaluation of 'q' here, otherwise it becomes a growing
chain of 'succ' applications.

E.g.

    qRem' q r = if r < n then (q, r)  else (qRem' $! succ q) (r - n)

Roman



More information about the Glasgow-haskell-users mailing list