Tech behind Tech

Raw information. No finesse :)

Posts Tagged ‘structure

Clojure defrecord deftype

with 2 comments


There are different ways to create a struct in clojure.

1) Using Clojure built in data structures

user> (def lotr {:title "Book title"
                 :author {
                          :first-name "first"
                          :last-name "last"}})
#'user/lotr
	

keyword-access

user> (:title lotr)
"Book title"

nested-access

user> (-> lotr :author :first-name)
"first"

2) Using defrecord

user> (defrecord Book [title author])
user.Book
user> (defrecord Person [first-name last-name])
user.Person
user> (def lotr (Book. "Book Title"
                       (Person. "first" "last")))
#'user/lotr

keyword-access

user> (:title lotr)
"Book title"

nested-access

user> (-> lotr :author :first-name)
"first"

As you can see, accessing map and defrecord is very similar. defrecord provides implementation of a persistent map.

3) Using deftype

PS: bad example ( I will explain why later )

user> (deftype Book [title author])
user.Book
user> (deftype Person [first-name last-name])
user.Person
user> (def lotr (Book. "Book Title"
                       (Person. "first" "last")))
#'user/lotr

Unlike defrecord, deftype does not provide implementation of a persistent map. So when you try to keyword-access , it won’t work

keyword-access

user> (:title lotr)
nil

It provides field access only

user> (.title lotr)
"Book Title"

I mentioned the above example for deftype is a bad example. Let me explain why. In OO, we have two set of classes. One set that defines language constructs like String and other that defines domain like Book. As defrecord provides implementation of a persistent map, it is better to use defrecord for realizing domain. Use deftype for realizing programming constructs.

Written by Siva Jagadeesan

November 15, 2010 at 10:58 am

Posted in Clojure

Tagged with , , , ,

Follow

Get every new post delivered to your Inbox.

Join 146 other followers

%d bloggers like this: