How do I define my type based on class so I can use that type in typecase and related expressions?

Consider this:

(defclass my-string ()
  ((data :initarg :data :type simple-string)
   (properties :initarg :properties :type interval-tree))
  (:documentation
   "Represents a string with properties."))

I would like to use my-string as a type in a typecase expression:

(defun upcase (obj)
  (typecase obj
    (my-string (string-upcase (slot-value obj 'data)))
    (string (string-upcase obj))
    (integer (char-upcase (code-char obj)))
    (character (char-upcase obj))
    (otherwise (error "Wrong type argument ~S" obj))))

I thought that classes are types, but obviously not, since the above is a compiler error. So I declared a type:

(deftype my-string (s) (typep s 'my-string))

which it seems I have to use like this (otherwise I get compilation error that typedef expects an argument):

(defun upcase (obj)
  (typecase obj
    ((my-string obj) (string-upcase (slot-value obj 'data)))
    (string (string-upcase obj))
    (integer (char-upcase (code-char obj)))
    (character (char-upcase obj))
    (otherwise (error "Wrong type argument ~S" obj))))

However SBCL deletes my code as unreachable! 🙂

How do I do this? How to properly declare a type for a class so I can use it in expressions where type declarations are usable?

I understand I can use struct instead of class, in which case the compiler generates code for the type, and the initial typecase “just works”:

(defstruct my-string
  data properties)

Macroexpanding and looking at the generated code didn’t really make more enlightened. I see this:

(SB-C:XDEFUN MY-STRING-P
     :PREDICATE
     NIL
     (SB-KERNEL::OBJECT)
   (TYPEP SB-KERNEL::OBJECT 'MY-STRING))

which does exactly what I did, but I don’t think that function is in the play, or am I wrong? Either they somehow associate structs with types internally, or I have missed some relevant part of the generated code? I am not very familiar with all this, so it is very likely as well.

A related question: what is the proper way to model a custom class that extends a built-in type like string in CommonLisp? Is it a better way to do the composition, as done in my-string, or is it perhaps better to inherit from some built-in CL string class? Based on this SX question and answers, it seems to me that inheritance is not the best way to model types, which is probably for the better, since we don’t like taxonomies as known from Java or old C++.

Finally, I wouldn’t even need typecase in this case if I made upcase a generic method that specialize on those types, the entire problem goes away, which I am fully aware of. However, I would like to learn more about types and classes, and how to model something like the above in CL.

Sorry if it is a bit long, and too many questions baked into one, I am just learning this. It feels like every question I have and experimenting for an answer opens 10 more questions :).

1

You are using deftype in a completely wrong way, so even though there is a better answer I’d like to focus on the part that was errorneous.

When you write (deftype u (s) (typep s 'u)), the first time you have no warning, and later you have an warning during compilation if you try again (with SBCL), because u in (typep s 'u) doesn’t have the expected number of arguments, defined by (deftype u (s) ...). This can be explained once we understand what deftype does.

First, in order for the (typep ...) call to make sense, you would need to write something like (typep v '(u s)) where v is a value, and (u s) is a type, parameterized by argument s. For example, (integer -2 -2) is such a type, it is a subset of integer with inclusive bounds:

(loop for i from -5 to 5 collect (list i (typep i '(integer -2 2))))
=> ((-5 NIL) (-4 NIL) (-3 NIL)
    (-2 T) (-1 T) (0 T) (1 T) (2 T) 
    (3 NIL) (4 NIL) (5 NIL))

The values with a T are the one when typep succeeds.
That’s because the function you define with deftype must return a type expression, typically you will find something like this:

(deftype octet () `(unsigned-byte 8))

Or

(deftype square-matrix (size type)
  `(array ,type (,size ,size)))

With the above definition, you can check if an array is actually a square matrix of integers:

(typep #2A((1 1) (2 2)) '(square-matrix 2 integer))

So square-matrix is a function producing a type specifier, as defined in 4.2.3 Type Specifiers.

Your my-string functions returns a generalized boolean (the result of typep), and the argument you wanted to give was a value (is s of type my-string), whereas s in a deftype argument is supposed to be used to express a type parameter, because you may have different variations of my-string (e.g. an explicit size parameter for your strings).

I hope this clarifies things a bit.


Also, a class is a type, so that works:

(defclass foo () ())

(defun bar (v)
  (typecase v
    (string "a string")
    (foo "a foo")))

1

Any CLOS class has a corresponding type.

CL-USER 3 > (defclass foo () (a b c))
#<STANDARD-CLASS FOO 801000157B>

CL-USER 4 > (type-of *)
STANDARD-CLASS

CL-USER 5 > (make-instance 'foo)
#<FOO 801000568B>

CL-USER 6 > (type-of *)
FOO

CL-USER 7 > (typep (make-instance 'foo) 'foo)
T

The class object of the class FOO has a type STANDARD-CLASS.

Instances of the class FOO are of type FOO.

Thus TYPECASE works with type names for CLOS classes:

CL-USER 8 > (dolist (object (list 1 "2" (make-instance 'foo)))
              (typecase object
                (number (format t "~% ~s is a number" object)) 
                (string (format t "~% ~s is a string" object)) 
                (foo    (format t "~% ~s is a CLOS object of class ~a"
                                object (class-of object)))))

 1 is a number
 "2" is a string
 #<FOO 8010000E2B> is a CLOS object of class #<STANDARD-CLASS FOO 81400243A3>

1

Class-wise behavior you do best implement using the multiple dispatch capability of Common Lisp CLOS (in this case, only single dispatch is needed) – by using generic function macros defgeneric and defmethod.

The good thing of using dispatch is anyway that you are much more flexible and the class-wise selection is extensible later (much better for maintenance). Not only that – if you import this code (e.g. as a package) – the code which uses this code (this code embedded in a package) – can still extend the dispatching (add new cases / new classes for the dispatch) which is a very powerful feature in programming.

And in as much dispatch is superior to typecase. Although typecase is of course faster in speed.

(defclass my-string ()
  ((data :initarg :data :type simple-string)
   (properties :initarg :properties :type interval-tree))
  (:documentation
   "Represents a string with properties."))

You write first a generic function using defgeneric:

(defgeneric upcase (obj)
  (:documentation "A generic function to upcase different types of objects."))

Then you write using defmethod each auf the clauses as separate method functions:

;; the general form is:
;; (defmethod upcase ((obj the-type-or-class-of-obj))
;;    ... specific code handling `obj` ...)


(defmethod upcase ((obj my-string))
  (string-upcase (slot-value obj 'data)))

(defmethod upcase ((obj string))
  (string-upcase obj))

(defmethod upcase ((obj integer))
  (char-upcase (code-char obj)))

(defmethod upcase ((obj character))
  (char-upcase obj))

(defmethod upcase ((obj t))
  (error "Wrong type argument ~S" obj))

Try the code by:

(let ((custom-string (make-instance 'my-string :data "hello" :properties nil)))
  (format t "Upcased my-string: ~A~%" (upcase custom-string)))

(format t "Upcased plain string: ~A~%" (upcase "world"))

(format t "Upcased integer: ~A~%" (upcase 97))  ; ASCII code for 'a'

(format t "Upcased character: ~A~%" (upcase #a))

(handler-case
    (upcase '(1 2 3))
  (error (e) (format t "Error: ~A~%" e)))

;; The output should be:
Upcased my-string: HELLO ; NIL
Upcased plain string: WORLD ; NIL
Upcased integer: A ; NIL
Upcased character: A ; NIL
Error: Wrong type argument (1 2 3) ; NIL

3

@coredump answered correctly.

In some cases, instead of typecase a dispatching via predicates might be meaningful.

You could write a macro:

(defmacro predcase (obj &rest clauses)
  "A version of TYPECASE that uses predicates."
  `(cond
     ,@(mapcar (lambda (clause)
                 (let ((predicate (car clause))
                       (body (cdr clause)))
                   `((,predicate ,obj) ,@body)))
               clauses)))

And then use it like this:

(defun upcase (obj)
  (predcase obj
    (my-string-p
     (string-upcase (slot-value obj 'data)))
    (stringp
     (string-upcase obj))
    (integerp
     (char-upcase (code-char obj)))
    (characterp
     (char-upcase obj))
    (t
     (error "Wrong type argument ~S" obj))))

But I know this was not actually the question.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật