RealFrac is the Haskell type class for real fractional values that can be converted to integral values or split into integral and fractional parts. It combines Real and Fractional, so types such as Float and Double support numeric conversion and division. section 10.1.1
Use the class methods when a fractional calculation must produce a whole-number result:
- round converts a fractional value to an Integral value, while ceiling and floor provide other rounding directions. section 10.1.1 section 10.5
- properFraction decomposes a fractional value into an integral part and a fractional remainder. section 10.1.1
- The resulting integral type is chosen through a type constraint, so a value can become an Int or Integer. section 10.1.1
Turning audio calculations into sample counts
An audio signal cannot contain half a sample, so fractional calculations need conversion to Int. With a 44,100 Hz sample rate, define: samplesPerPeriod :: Hz -> Int; samplesPerPeriod hz = round $ sampleRate / hz. Similarly, samplesPerSecond duration = round $ duration * sampleRate. In GHCi, round (3.1415 :: Double) :: Integer produces 3. section 10.1.1
Listing 10.1 Types and helper functions for dealing with signals
type Sample = Double #1 type Signal = [Sample] #1 type Hz = Double #1 type Seconds = Double #1 sampleRate :: Double #2 sampleRate = 44100 samplesPerPeriod :: Hz -> Int samplesPerPeriod hz = round $ sampleRate / hz #3 samplesPerSecond :: Seconds -> Int samplesPerSecond duration = round $ duration * sampleRate #4
Inspect the complete signal types and helper functions that use RealFrac conversion in an audio calculation. section 10.1.1
