On Sun, 23 Sep 2007, Thomas Conway wrote:

In Prelude there is a function properFraction which splits a RealFrac
into its integer part and its fractional part. You can use this to
implement fmod. Assuming properFraction is efficient (which it
probably isn't), you can implement fmod really quite efficiently.

In particular, x `fmod` 1.0 == (snd . properFraction) x

Unfortunately, properFraction doesn't work well with negative numbers. I get

Prelude> properFraction (-0.3)
(0,-0.3)

but usually I need

Prelude> properFraction (-0.3)
(-1,0.7)


Thus I defined a work-around:

splitFraction x =
   let (n,f) = properFraction x
   in  if x>=0 || f==0
         then (fromInteger n,   f)
         else (fromInteger n-1, f+1)


See also
  http://www.haskell.org/haskellwiki/Things_to_avoid#Forget_about_quot_and_rem
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to