liveBook · Manning

Fractional

As explained in Learn Haskell by Example

Fractional is a Haskell type class for numeric types that support division and reciprocals.

Fractional is a Haskell numeric type class for values that support division, reciprocals, and conversion from Rational values. It extends Num and commonly applies to Float and Double. section 10.1.1

Use Fractional operations when calculations require non-integer results:

  • (/) divides two values, as in sampleRate / hz. section 10.1.1
  • recip produces a reciprocal, equivalent to dividing one by a value. section 10.1.1

Calculating samples for a sound

A signal with a sample rate of 44,100 samples per second can calculate the samples in one period with samplesPerPeriod hz = round $ sampleRate / hz. The division uses Fractional arithmetic, while round converts the resulting Double to Int.

ghci> :i Integral
type Integral :: * -> Constraint
class (Real a, Enum a) => Integral a where
  quot :: a -> a -> a
  rem :: a -> a -> a
  div :: a -> a -> a
  mod :: a -> a -> a
  quotRem :: a -> a -> (a, a)
  divMod :: a -> a -> (a, a)
  toInteger :: a -> Integer
  {-# MINIMAL quotRem, toInteger #-}
instance Integral Word
instance Integral Integer
instance Integral Int
ghci> :i Fractional
type Fractional :: * -> Constraint
class Num a => Fractional a where
  (/) :: a -> a -> a
  recip :: a -> a
  fromRational :: Rational -> a
  {-# MINIMAL fromRational, (recip | (/)) #-}
instance Fractional Float
instance Fractional Double

Inspect the Fractional class declaration and compare its methods and Float and Double instances. section 10.1.1

How Learn Haskell by Example covers it

How deep it goes
Defines the class methods and instances, then applies division in a signal calculation without detailing numeric implementation internals.
Examples
Demonstrates (/), recip, Float and Double instances, and samplesPerPeriod for digital audio signals.
What it assumes
Assumes Num arithmetic and distinguishes it from Integral division while teaching Fractional operations through examples.
What you can do after
Apply it via Haskell type signatures to divide floating-point values and combine division with integer conversion.
How it connects
Connects Fractional with Num, Integral, RealFrac, and Rational through numeric operations and conversions.

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.