1
votes
  (declare storage)
    (defn initialize-storage []) ((def storage 
       (make-array Integer/TYPE 3  3))
      (for [ i (range 1 3 )
             j (range 1 3 )]
               (aset (aget storage i) j 100)
         )
      (use 'clojure.pprint)
      (pprint storage)
      )

I get the below

ClassCastException [[I cannot be cast to clojure.lang.IFn  clojure.lang.Var.fn (Var.java:378)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

The idea is to set all the values to 100

I suspect my usage in a 2-d array context of aset is not correct but that was what i got after a fair few hours of searching.

Edit::

(use 'clojure.pprint)
 (defn initialize-storage []) ((def storage 
           (make-array Integer/TYPE 3  3))
          (for [ i (range 1 3 )
                 j (range 1 3 )]
                   (aset-int storage i j 100))          
          (pprint storage))

Now, that I have set my storage. I want to have another function, which will call this function and then proceed to do other tasks. But I get an exception that cannot find initialise-storage.

How does having a namespace help in this regard? Are the functions aware of each other's presence, or do we need to make them public and expose? Should all of these be inside the namespace? Then if where do i put the (def ..), since that throws an exception as well ?

1

1 Answers

2
votes

for is lazy so you need to wrap it in a (dorun)

(dorun (for [ i (range 1 3 )
              j (range 1 3 )]
          (aset (aget storage i) j 100)))

otherwise the asets will not actually happen

aset can work directly on 2d arrays:

 (aset-int array x y 42)

the class cast exception is being caused by the

((def storage 
   (make-array Integer/TYPE 3  3))

which is attempting to invoke the result of defining a var as if it was a function.


(use 'clojure.pprint)
(defn initialize-storage []) ; empty function deffinition here

( (def storage ;extra paren here
    (make-array Integer/TYPE 3  3))

  (for [ i (range 1 3 ) ; leaves the first row unmodified
       j (range 1 3 )] ; leaves the first columb unmodified
   (aset-int storage i j 100)) ;unevaluated for loop here
 (pprint storage) ) ; extra parens here

perhaps this is closer to what you where looking for:

(use 'clojure.pprint)
(def storage (make-array Integer/TYPE 3  3))
(defn initialize-storage []
  (doall (for [ i (range 0 3 )
               j (range 0 3 )]
           (aset-int storage i j 100))))          
(pprint storage)