liveBook · Manning

RealFrac

As explained in Learn Haskell by Example

RealFrac is the Haskell type class for fractional real-number types that support conversion to integral values and decomposition into integral and fractional parts.

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

How Learn Haskell by Example covers it

How deep it goes
Defines the class hierarchy and methods, then demonstrates round in a sample-count calculation without exploring instance implementation.
Examples
Uses 44.1 kHz signal calculations, sample-count helper functions, and the GHCi expression round (3.1415 :: Double).
What it assumes
Assumes basic numeric types and type classes, while introducing RealFrac alongside Real, Fractional, and Integral.
What you can do after
Apply it via round, ceiling, floor, or properFraction when fractional values must become integral results.
How it connects
Connects Real, Fractional, Integral, properFraction, round, ceiling, and floor through numeric conversion and decomposition.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.