{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## 8.5 Class and instance declarations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "class Eq a where\n", " (==), (/=) :: a -> a -> Bool\n", " x /= y = not (x == y)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "instance Eq Bool where\n", " False == False = True\n", " True == True = True\n", " _ == _ = False\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Bool is an instance of the Eq class, with (==) defined as above.\n", "\n", "Only types that are defined using the data or newtype mechanisms can be made instances of classes.\n", "\n", "Classes can also be extended to form new classes. For example, the class Ord of types whose values are totally ordered is declared as an extension of Eq class." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "class Eq a => Ord a where\n", " (<), (<=), (>), (>=) :: a -> a -> Bool\n", " min, max :: a -> a -> a\n", " min x y | x <= y = x\n", " | otherwise = y\n", " max x y | x <= y = y\n", " | otherwise = x" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "instance Ord Bool where\n", " False < True = True\n", " _ < _ = False\n", " \n", " b <= c = (b < c) || (b == c)\n", " b > c = c < b\n", " b >= c = c <= b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Derived instances" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When new types are declared, it is usually appropriate to make them instances of a number of built-in classes using the \"deriving\" clause.\n", "```\n", "data Bool = False | True deriving (Eq, Ord, Show, Read)\n", "```" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/html": [ "