liveBook · Manning

Num

As explained in Type-Driven Development with Idris

Num is the Idris interface for types that support numeric operations, including addition, multiplication, and conversion from integer literals.

Num is an Idris interface for types that support numeric operations. A function typed `Num ty => ty -> ty` can use arithmetic on `ty`, while remaining generic over which numeric type it receives. section 2.2.4

Num provides addition, multiplication, and conversion from integer literals. Related interfaces group other numeric operations:

  • Neg provides negation, subtraction, and absolute value for types that can be negative. section 7.2.2
  • Integral provides division and remainder operations for integer types. section 7.2.2
  • Fractional provides division and reciprocal operations for fractional types. section 7.2.2

Generalize a doubling function

A `double : ty -> ty` definition cannot use `+` for an unconstrained type. Adding the constraint, as in `double : Num ty => ty -> ty`, permits `double x = x + x` for types with a Num implementation. section 2.2.4

interface Num ty where                              #1
    (+) : ty -> ty -> ty
    (*) : ty -> ty -> ty
    fromInteger : Integer -> ty                     #2
interface Num ty => Neg ty where                    #3
    negate : ty -> ty
    (-) : ty -> ty -> ty
    abs : ty -> ty
interface Num ty => Integral ty where               #4
    div : ty -> ty -> ty
    mod : ty -> ty -> ty
interface Num ty => Fractional ty where             #5
    (/) : ty -> ty -> ty
    recip : ty -> ty
    recip x = 1 / x

The interface definitions show Num's methods and how Neg, Integral, and Fractional build on Num. section 7.2.2

Implementing Num for an expression type lets standard operators and integer literals construct expressions. An Expr example uses `+`, `*`, and literals to build an expression that evaluates to 42. section 7.2.2

How Type-Driven Development with Idris covers it

How deep it goes
Defines Num's methods and related numeric interfaces, then demonstrates an Expr implementation; it does not detail interface definitions generally.
Examples
Uses a generic doubling function and an arithmetic-expression type built with operators and integer literals.
What it assumes
Assumes generic type variables and constraints, while showing how Num restricts a type to numeric operations.
What you can do after
Build an arithmetic-expression type that uses standard operators and integer literals through a Num implementation.
How it connects
Connects Num to interfaces, integer literals, Neg, Integral, and Fractional.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Type-Driven Development with Idris. The section links point to the parts of the book it draws on.