LISP - CERRADO

Common LISP es anterior al avance de la programación orientada a objetos en un par de décadas. Sin embargo, la orientación a objetos se incorporó en una etapa posterior.

Definición de clases

los defclassmacro permite crear clases definidas por el usuario. Establece una clase como tipo de datos. Tiene la siguiente sintaxis:

(defclass class-name (superclass-name*)
   (slot-description*)
   class-option*))

Las ranuras son variables que almacenan datos o campos.

Una descripción de ranura tiene la forma (nombre de ranura opción de ranura *), donde cada opción es una palabra clave seguida de un nombre, expresión y otras opciones. Las opciones de tragamonedas más utilizadas son:

  • :accessor nombre de la función

  • :initform expresión

  • :initarg símbolo

Por ejemplo, definamos una clase Box, con tres ranuras de longitud, anchura y altura.

(defclass Box () 
   (length 
   breadth 
   height)
)

Proporcionar acceso y control de lectura / escritura a una ranura

A menos que las ranuras tengan valores a los que se pueda acceder, leer o escribir, las clases son bastante inútiles.

Puede especificar accessorspara cada espacio al definir una clase. Por ejemplo, tome nuestra clase Box -

(defclass Box ()
   ((length :accessor length)
      (breadth :accessor breadth)
      (height :accessor height)
   )
)

También puede especificar por separado accessor nombres para leer y escribir una ranura.

(defclass Box ()
   ((length :reader get-length :writer set-length)
      (breadth :reader get-breadth :writer set-breadth)
      (height :reader get-height :writer set-height)
   )
)

Crear instancia de una clase

La función genérica make-instance crea y devuelve una nueva instancia de una clase.

Tiene la siguiente sintaxis:

(make-instance class {initarg value}*)

Ejemplo

Creemos una clase Box, con tres espacios, largo, ancho y alto. Usaremos tres accesos de ranura para establecer los valores en estos campos.

Cree un nuevo archivo de código fuente llamado main.lisp y escriba el siguiente código en él.

(defclass box ()
   ((length :accessor box-length)
      (breadth :accessor box-breadth)
      (height :accessor box-height)
   )
)
(setf item (make-instance 'box))
(setf (box-length item) 10)
(setf (box-breadth item) 10)
(setf (box-height item) 5)
(format t "Length of the Box is ~d~%" (box-length item))
(format t "Breadth of the Box is ~d~%" (box-breadth item))
(format t "Height of the Box is ~d~%" (box-height item))

Cuando ejecuta el código, devuelve el siguiente resultado:

Length of the Box is 10
Breadth of the Box is 10
Height of the Box is 5

Definición de un método de clase

los defmethodmacro le permite definir un método dentro de la clase. El siguiente ejemplo extiende nuestra clase Box para incluir un método llamado volumen.

Cree un nuevo archivo de código fuente llamado main.lisp y escriba el siguiente código en él.

(defclass box ()
   ((length :accessor box-length)
      (breadth :accessor box-breadth)
      (height :accessor box-height)
      (volume :reader volume)
   )
)

; method calculating volume   

(defmethod volume ((object box))
   (* (box-length object) (box-breadth object)(box-height object))
)

 ;setting the values 

(setf item (make-instance 'box))
(setf (box-length item) 10)
(setf (box-breadth item) 10)
(setf (box-height item) 5)

; displaying values

(format t "Length of the Box is ~d~%" (box-length item))
(format t "Breadth of the Box is ~d~%" (box-breadth item))
(format t "Height of the Box is ~d~%" (box-height item))
(format t "Volume of the Box is ~d~%" (volume item))

Cuando ejecuta el código, devuelve el siguiente resultado:

Length of the Box is 10
Breadth of the Box is 10
Height of the Box is 5
Volume of the Box is 500

Herencia

LISP le permite definir un objeto en términos de otro objeto. Se llamainheritance.Puede crear una clase derivada agregando características nuevas o diferentes. La clase derivada hereda las funcionalidades de la clase principal.

El siguiente ejemplo explica esto:

Ejemplo

Cree un nuevo archivo de código fuente llamado main.lisp y escriba el siguiente código en él.

(defclass box ()
   ((length :accessor box-length)
      (breadth :accessor box-breadth)
      (height :accessor box-height)
      (volume :reader volume)
   )
)

; method calculating volume   
(defmethod volume ((object box))
   (* (box-length object) (box-breadth object)(box-height object))
)
  
;wooden-box class inherits the box class  
(defclass wooden-box (box)
((price :accessor box-price)))

;setting the values 
(setf item (make-instance 'wooden-box))
(setf (box-length item) 10)
(setf (box-breadth item) 10)
(setf (box-height item) 5)
(setf (box-price item) 1000)

; displaying values
(format t "Length of the Wooden Box is ~d~%" (box-length item))
(format t "Breadth of the Wooden Box is ~d~%" (box-breadth item))
(format t "Height of the Wooden Box is ~d~%" (box-height item))
(format t "Volume of the Wooden Box is ~d~%" (volume item))
(format t "Price of the Wooden Box is ~d~%" (box-price item))

Cuando ejecuta el código, devuelve el siguiente resultado:

Length of the Wooden Box is 10
Breadth of the Wooden Box is 10
Height of the Wooden Box is 5
Volume of the Wooden Box is 500
Price of the Wooden Box is 1000