[Haskell-cafe] C's fmod in Haskell

Henning Thielemann lemming at henning-thielemann.de
Mon Sep 24 07:49:41 EDT 2007

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)

but usually I need

Prelude> properFraction (-0.3)

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

More information about the Haskell-Cafe mailing list