ashutosh raina
ashutosh raina

Reputation: 9314

How to define a list of Types in clojure?

I want to have something to define my UDT so the following

(defrecord Foo [a b])

Now i can declare an instance of this type as

(def f (Foo. 10 20))

but how do i have a java like array of these in clojure.

I want to have new ArrayList<Foo>() (or something close), so that I can call Add method repeatedly to add new Foo to the list.

Can't seem to find a way to do that.

Edit:

I need to tell clojure to map my things to the keys of Foo. So, i need a way to to say go through my foo-data, and then make an ArrayList Out of it of type Foo

(defrecord Foo [a b c])
(def foo-data
  [ "foo1"   1 8
    "foo2"   2 7
    "foo3"   3 6
    "foo4"   4 5])

I can access these by a doseq but then i need to make a ArrayList and then work with that to do some manipulation.

Upvotes: 2

Views: 782

Answers (3)

Jim Downing
Jim Downing

Reputation: 1491

If you don't need to pass the ArrayList back to something strongly typed straight away, it's best to manipulate your data structure in Clojure. I find the "Seq In, Seq Out" section of http://clojure.org/cheatsheet a handy reference. If you prefer to learn by example, http://www.4clojure.com is awesome for learning data structure transformations.

Upvotes: 1

mikera
mikera

Reputation: 106401

I'd suggest using the built-in Clojure functionality which automatically creates a constructor function:

 (defrecord Foo [a b])

 (->Foo 1 2)   ;; auto-generated constructor
 => #user.Foo{:a 1, :b 2}

Then you can use standard Clojure higher order functions to construct whatever collection of Foos you like, e.g.

(def foo-data [["Bob" 2] 
               ["Fred" 4] 
               ["Len" 6]])

(into [] (map (partial apply ->Foo) foo-data))
=> (A vector of Foos with the provided data)

Upvotes: 6

Ankur
Ankur

Reputation: 33657

It will be as simple as:

user=> (import 'java.util.ArrayList)
user=> (def data (ArrayList.)) 
#'user/data
user=> (.add data (Foo. 10 20))

I would suggest to use clojure data structure like vector for such scenarios.

Vector example:

user=> (def data (atom []))
#'user/data
user=> (swap! data conj (Foo. 10 20)) ;Add item to data vector

Upvotes: 3

Related Questions