HomeMathEmailBlogGitHub

Deftype in Clojure

2023-05-23

deftype in Clojure is a way to abstract data away into a structure. It is comparable to struct in C.

An example of struct in C

typedef struct Rectangle {
    int length;
    int width;
} Rectangle;

is easily convertible to an example of deftype in Clojure

(deftype Rectangle [length width])

and the uses are very similar as well

Rectangle r = {5, 4};
printf("%d", r.length*r.width);
(let [r (Rectangle. 5 4)]
     (println (* (.length r) (.width r))))