Ok, I think I cracked it but as usual someone else might come up with a cleaner approach...:-)

(defn matrix [dim & dim-lengths]
{:pre [(not (nil? dim))]} ;;cannot accept
(let [bindings (map #(vector (gensym) `(range ~%)) dim-lengths)
      symbols  (mapv first bindings)
      counts   (inc (count symbols)) ;;include dim in count
      curr-sym (or (first symbols) (gensym))]
(if (> counts 1) ;;more dimensions?
  `(for ~(vector curr-sym `(range ~dim))
~(apply matrix (first dim-lengths) (next dim-lengths))) ;;recurse for each element `(for ~(vector curr-sym `(range ~dim)) ~curr-sym)))) ;;revert to plain 'for'


The behaviour is as expected for matrices and the precondition is very informative with regards to the failing condition... I'm really curious to see any different approaches...

Jim



On 05/02/13 15:09, Jim foo.bar wrote:
I do hate writing code on thunderbird!!! '(< counts 1)' should obviously be '(> ~counts 1)'...

Jim


On 05/02/13 15:03, Jim foo.bar wrote:
Hi all,

I 'm a bit confused with this - I'm trying to think but I can't!!! Probably cos I've not had any food yet! Up till now I thought I could construct matrices with 'for'...So (for [i (range 3)] i) gives us a 1d structure (a list)... (for [i (range 3) j (range 4)] [i j]) gives us a 2d structure (list of vectors)

On that basis I wrote the following little macro thinking I'd be bale to create matrices with arbitrary dimensions:

(defn matrix [& dim-lengths]
(let [bindings (vec (mapcat #(vector (gensym) `(range ~%)) dim-lengths))
      symbols  (mapv first (partition 2 bindings))
      counts (count symbols)]
  `(for ~bindings  (if (< counts 1) ~symbols (first ~symbols)))))

Now, even though this expands to the 'for' I want I'm starting to think this is not the right approach for matrices...all I get is 2d structures regardless of how many dimensions I pass in...

any ideas anyone?

Jim






--
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- You received this message because you are subscribed to the Google Groups "Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to