typestar

Protocolos y records en Clojure

Declara una operación de cobro como protocolo y dos tipos de record la responden distinto.

;; A protocol names operations without saying how a type carries
;; them out. A record is a map with named fields, and it can satisfy
;; the protocol inline with its own method body.
(defprotocol Billable
  (monthly-cost [this] "Charge in dollars for one month."))

(defrecord Metered [rate units]
  Billable
  (monthly-cost [this] (* rate units)))

(defrecord Flat [fee]
  Billable
  (monthly-cost [this] fee))

;; Callers name only the protocol; the record picks the behavior.
(def accounts [(->Metered 0.14 320) (->Flat 45.0)])
(doseq [account accounts]
  (println (format "%-8s %7.2f" (.getSimpleName (class account))
                   (monthly-cost account))))

Cómo funciona

  1. (defprotocol Billable abre la declaración, y la línea (monthly-cost [this] nombra la operación sin implementarla.
  2. (defrecord Metered [rate units] lista los campos, y la línea Billable de abajo abre la implementación en línea.
  3. (doseq [account accounts] llama a (monthly-cost account) sobre ambos records, y cada tipo corre su cuerpo.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
19
Caracteres a escribir
635
Tokens
90
Ritmo de tres estrellas
70 tpm

Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 77 segundos.

Escribe este fragmento

Paso 3 de 3 en Estado y records; paso 24 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →