Last active
          October 13, 2016 07:42 
        
      - 
      
- 
        Save svetlyak40wt/0de4a633a89577906b9915facce9b96d to your computer and use it in GitHub Desktop. 
    Пример проверки дополнительных условий для типов в Common Lisp
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | ;;; Пример проверки дополнительных условий для типов в Common Lisp | |
| (defun equidimensional (a) | |
| (or (< (array-rank a) 2) | |
| (apply #'= (array-dimensions a)))) | |
| ;; тут мы определяем тип, который представляет собой | |
| ;; матрицу, все размерности которой одинаковы | |
| (deftype square-matrix (&optional type size) | |
| `(and (array ,type (,size ,size)) | |
| (satisfies equidimensional))) | |
| ;; квадратная матрица 2x2 | |
| (defparameter *a1* (make-array '(2 2) :initial-contents '((1 2) (3 4)))) | |
| ;; матрица 2x3 | |
| (defparameter *a2* (make-array '(2 3) :initial-contents '((1 2 3) (4 5 6)))) | |
| (defun square-p (array) | |
| ;; сравниваем тип данной нам матрицы с квадратной | |
| (typecase array | |
| (square-matrix t) | |
| (t nil))) | |
| ;; тип правильный | |
| (square-p *a1*) => T | |
| ;; тип неверный | |
| (square-p *a2*) => NIL | |
| (defun process-square (matrix) | |
| "Эта функция работает только с квадратными матрицами." | |
| (declare (type square-matrix matrix) | |
| (ignorable matrix)) | |
| (print "Обрабатываем квадратную матрицу")) | |
| (process-square *a1*) ; => Напечатает "Обрабатываем квадратную матрицу" | |
| ;; если тип не соответствует, в рантайме возникнет исключение | |
| (process-square *a2*) ; => Сигнализирует condition | |
| ;; The value | |
| ;; #2A((1 2 3) (4 5 6)) | |
| ;; is not of type | |
| ;; (AND (ARRAY * (* *)) | |
| ;; (SATISFIES CL-USER::EQUIDIMENSIONAL)) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment