Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use deftype in Clojure?

Tags:

Yesterday, Rich pulled the 'new' branch of Clojure into master. We are now embracing the beauty that is deftype and defprotocol. Of course, I, coming from Haskell, am very tempted to define types like I would in Haskell, which would be for virtually everything short of a throwaway tuple, but I don't think it works like that in Clojure world ;). In the Common Mistakes thread for Clojure, one guy mentioned that overusing structs was a mistake he made when he first started, coming from OOP. Since deftypes seem to be similar to structs, I was wondering if the same thing applies there.

So, my question is: when is it a good time to use deftype?

like image 982
Rayne Avatar asked Jan 12 '10 10:01

Rayne


People also ask

When to use deftype Clojure?

Summary: There are two commonly used ways to create new data types in Clojure, deftype and defrecord . They are similar but are intended to be used in two distinct use cases. deftype is for programming constructs and defrecord is for domain constructs.

What is Defrecord?

defrecord creates an immutable persistent map which implements a protocol. Which to use depends on what you want. Do you want a full ClojureScript data structure? Then use a record. Do you just want a bare-bones thing that does nothing but satisfy a protocol?

Are there classes in Clojure?

Clojure has gen-class, reify, proxy and also deftype and defrecord to define new class-like datatypes.

What is a Clojure protocol?

A protocol is a named set of named methods and their signatures, defined using defprotocol: (defprotocol AProtocol "A doc string for AProtocol abstraction" (bar [a b] "bar docs") (baz [a] [a b] [a b c] "baz docs")) No implementations are provided. Docs can be specified for the protocol and the functions.


1 Answers

One area deftype shines is performance. Methods of protocols are very fast on a deftype. Also deftype may have primitive fields, so no boxing anymore when crunching numbers...

Another area might be Java interoperation, since deftype can implement interfaces (and if AOT compiled) have a named class.

In general is the basic idea to define abstractions with protocols and to implement them with deftype.

Rich details his motivation here: http://www.assembla.com/wiki/show/clojure/Datatypes

like image 118
kotarak Avatar answered Mar 01 '23 09:03

kotarak