typestar

Derivar instancias en Haskell

Una cláusula deriving en un tipo suma aporta gratis Show, Eq, Ord, Enum y Bounded.

module Priorities where

-- One deriving clause hands you five instances at once.
data Priority = Low | Normal | High | Urgent
  deriving (Show, Eq, Ord, Enum, Bounded)

-- Bounded supplies the endpoints; Enum walks the range between them.
everyPriority :: [Priority]
everyPriority = [minBound .. maxBound]

-- Ord ranks constructors in declaration order, so Urgent is the largest.
needsPaging :: [Priority]
needsPaging = filter (> Normal) everyPriority

-- Enum numbers the constructors from zero upward.
ticketWeight :: Priority -> Int
ticketWeight = fromEnum

Cómo funciona

  1. data Priority = Low | Normal | High | Urgent gana cinco instancias con un deriving (Show, Eq, Ord, Enum, Bounded).
  2. everyPriority abarca el tipo entero como [minBound .. maxBound], con los extremos de Bounded y el recorrido de Enum.
  3. filter (> Normal) se apoya en el Ord derivado, y ticketWeight = fromEnum numera los constructores desde cero.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
17
Caracteres a escribir
559
Tokens
62
Ritmo de tres estrellas
75 tpm

Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 50 segundos.

Escribe este fragmento

Paso 1 de 3 en Clases de tipos; paso 19 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →