Several constructors in common lisp

Is it possible to use classes with several constructors and / or copy constructors - lisp? That is, to create a class for a new vector - "vecr" to represent three-dimensional vectors of real numbers, I would like to define a new class that can be initialized in several ways:

(vecr 1.2) ==> #(1.2 1.2 1.2) 

or

 (vecr 1.2 1.4 3.2) ==> #(1.2 4.3 2.5) 

or

 (vecr) ==> #(0.0 0.0 0.0) 
+4
source share
4 answers

I cannot figure out how to comment on the above:

This function works well to create a default # (0.0 0.0 0.0) vector type. However (vecr 1.0) ==> # (1.0 0.0 0.0) instead of the expected # (1.0 1.0 1.0). I believe the way around this is to check if all three or just one of the optional arguments were there. - Shamster 6 hours ago

You can do it:

 (defun vecr (&optional (x 0.0) (yx) (zy)) (vector xyz)) 
+7
source

One easy way:

 (defun vecr (&optional (x 0.0) (y 0.0 y-supplied-p) (z 0.0)) (if y-supplied-p (vector xyz) (vector xxx))) 
+4
source

There are no “constructors” or “copy constructors” in Lisp in the same sense as in C ++.

Classes in Lisp are instantiated by a make instance and passed by reference. This means that copying does not occur.

As for your question, you can create a function that creates an instance of the class and passes the necessary arguments to the make-instance function or otherwise initializes the instance.

In your case, the easiest way is to have this function:

 (defun vecr (&optional (x 0.0) (y 0.0) (z 0.0)) (vector xyz)) 
+3
source

See the MAKE-ARRAY function:

 CL-USER 1 > (make-array 3 :initial-element 1.2) #(1.2 1.2 1.2) CL-USER 2 > (make-array 3 :initial-contents '(1.2 1.4 3.2)) #(1.2 1.4 3.2) CL-USER 3 > (make-array 3) #(NIL NIL NIL) 
+3
source

All Articles