liveBook · Manning

Rational number

As explained in Learn Haskell by Example

Rational is a Haskell numeric type representing ratios of integers.

A rational number represents a ratio of integers exactly, making it a practical choice when fractional values must remain precise. In Haskell, Rational is an alias for Ratio Integer, while Ratio can use other integral types. section 10.4.2 section 10.1.1

Use the Ratio API to construct and calculate with rational values:

  • Write numerator % denominator; the operator accepts Integral values, such as Int, Integer, or Natural, but not Double. section 10.4.2
  • Use ordinary Num operations for arithmetic, including addition, subtraction, and multiplication. section 10.4.2
  • Choose Natural when a domain value must be nonnegative, but guard calculations because subtracting too far can throw an exception. section 10.4.2

Representing musical note lengths

import Data.Ratio (Ratio, (%)) import Numeric.Natural (Natural) type Notelength = Ratio Natural whole, half, quarter :: Notelength whole = 1 % 1 half = 1 % 2 quarter = 1 % 4 dotted :: Notelength -> Notelength dotted x = x + x * (1 % 2) triplet :: Notelength -> Notelength triplet x = x * (2 % 3) A half note becomes 3 % 4 when dotted and 1 % 3 when treated as a triplet. section 10.4.2

ghci> import Data.Ratio
ghci> :k Ratio
Ratio :: * -> *
ghci> 1 % 2 :: Ratio Int
1 % 2
ghci> 3 % 2 + 1 % 2 :: Ratio Int
2 % 1
ghci> 4 % 5 - 2 % 10 :: Ratio Int
3 % 5

Try constructing and calculating Ratio values directly in GHCi to see normalization and inferred kinds. section 10.4.2

How Learn Haskell by Example covers it

How deep it goes
Defines Ratio, its Integral parameter, arithmetic support, and Natural pitfalls, but stops short of broader implementation internals.
Examples
Uses whole, half, quarter, dotted, triplet, and GHCi arithmetic examples for musical note lengths.
What you can do after
Build exact duration values and calculate dotted notes or tuplets with typed ratios.
How it connects
Connects Ratio with Rational, Integral, Num, Natural, Real, and toRational.

Also explained in

Compare how 3 books explain rational number →

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.