Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple constructors in common lisp

Can classes have multiple constructors and/or copy constructors in common-lisp? That is - in order to create a class for a new vector - "vecr" to represent 3-d vectors of real numbers, I'd like to define the new class that can be initialized in multiple 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)
like image 645
Shamster Avatar asked Dec 04 '22 14:12

Shamster


1 Answers

I can't figure out how to comment on what was said above:

This function works well to create a default #(0.0 0.0 0.0) type of vector. However, (vecr 1.0) ==> #(1.0 0.0 0.0) instead of the intended #(1.0 1.0 1.0). I suppose the way around this is to check whether all three were passed, or just one of the optional arguments. – Shamster 6 hours ago

You can do this:

(defun vecr (&optional (x 0.0) (y x) (z y))
  (vector x y z))
like image 195
lnostdal Avatar answered Feb 11 '23 05:02

lnostdal