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
data Priority = Low | Normal | High | Urgentgana cinco instancias con underiving (Show, Eq, Ord, Enum, Bounded).everyPriorityabarca el tipo entero como[minBound .. maxBound], con los extremos de Bounded y el recorrido de Enum.filter (> Normal)se apoya en el Ord derivado, yticketWeight = fromEnumnumera los constructores desde cero.
Palabras clave y builtins usados aquí
BoundedEnumEqHighIntLowNormalOrdPriorityShowUrgentdataderivingmodulewhere
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.
Paso 1 de 3 en Clases de tipos; paso 19 de 27 en Fundamentos del lenguaje.