Re: print-base / print-radix?
On Jul 5, 9:02 pm, Tom Faulhaber wrote: > Parth, > > I've created a little wrapper as promised at:http://gist.github.com/141001. > > It gives you my-pprint: > > user> (binding [*print-base* 2] (my-pprint (range 10))) > (0 1 10 11 100 101 110 111 1000 1001) > nil > user> > Thanks Tom. This works beautifully :) Here is the example that earlier example in the thread: user=> (binding [wrap-base/*print-base* 16] (wrap-base/my-pprint (decode :b32 (test-ops 3 {:inst {:prefix (), :code (c7 45 f8 a 0 0 0), :op :movl, :args [{:type :Ev-mem, :arg {:reg :ebp, :disp -8}} a]}, :more ()} nil user=> > While doing this, I realized to my horror that ~r doesn't do 0 > correctly for non-standard bases. I'll fix that soon. > > Also, I've started to implement *print-radix* and *print-base* for > real in cl-format and the pretty printer, so those should be available > soon. > Fantastic ... pprint just keeps getting better :) Regards, Parth > Enjoy, > > Tom > > On Jul 3, 3:16 am, Parth wrote: > > > On Jul 3, 11:25 am, Tom Faulhaber wrote: > > > > Parth, > > > > I was thinking about this a little more today and I came up with a way > > > to extend the pretty printer easily to support *print-radix* with a > > > little wrapper. I'll try to get a chance to write it up for you > > > tomorrow. > > > > Tom > > > Sounds perfect. Thanks very much :) > > > Regards, > > Parth > > > > On Jul 2, 6:29 pm, Parth wrote: > > > > > On Jul 3, 6:15 am, Parth wrote: > > > > > > Tom, Chouser, Thanks for your responses. > > > > > > As of now I am doing the same thing as suggested. > > > > > However, this tends be become painful the moment structures > > > > > start to nest. For e.g. I am using Clojure to decode a bit > > > > > of assembly and below is what I end up doing to see the > > > > > values of interest in hex: > > > > > > user=> (decode :b32 (nth test-ops 3)) > > > > > {:inst {:prefix (), :code (199 69 248 10 0 0 0), :op :movl, :args > > > > > [{:type :Ev-mem, :arg {:reg :ebp, :disp -8}} 10]}, :more ()} > > > > > user=> (def r (decode :b32 (nth test-ops 3))) > > > > > #'user/r > > > > > user=> (map hex (get-in r [:inst :code])) > > > > > ("c7" "45" "f8" "a" "0" "0" "0") > > > > > user=> (hex (second (get-in r [:inst :args]))) > > > > > "a" > > > > > user=> > > > > > > Basically, I need to extract each number seq or value > > > > > individually and print it in hex for every instruction I > > > > > decode and view. > > > > > > This isn't too much fun to do in the middle of a debug session :) > > > > > > Having something like *print-base* would be ideal IMHO > > > > > would make scenarios like this really easy as one could > > > > > simply do: > > > > > > user=> (set! *print-base* 16) > > > > > user=> (decode :b32 (nth test-ops 3)) > > > > > {:inst {:prefix (), :code (c7 47 f8 a 0 0 0), :op :movl, :args > > > > > [{:type :Ev-mem, :arg {:reg :ebp, :disp f8}} a]}, :more ()} > > > > > > In the absence of this I thought of writing a function > > > > > that would take an arbitrary Clojure structure/coll and print > > > > > it out in the manner like above. But then it won't > > > > > be much different from pprint with radix support but without > > > > > the pretty part. > > > > > > I suppose what I am hoping is that a feature request for > > > > > *print-base* sort of a mechanism get considered > > > > > for Clojure as it makes scenarios like the above very > > > > > easy to deal with. Any chance of this being somewhere > > > > > on the Clojue todo? :) > > > > > Rich, > > > > > If this is something you think would be a good addition > > > > to Clojure I could give a shot at creating a patch for > > > > this (with a CA of course). Please let me know. > > > > > I think rather than a generic radix support, if > > > > we have hex, bin and octal supported, most uses > > > > cases should be covered. > > > > > Regards, > > > > Parth > > > > > > I will probably create a
Re: print-base / print-radix?
On Jul 3, 11:25 am, Tom Faulhaber wrote: > Parth, > > I was thinking about this a little more today and I came up with a way > to extend the pretty printer easily to support *print-radix* with a > little wrapper. I'll try to get a chance to write it up for you > tomorrow. > > Tom > Sounds perfect. Thanks very much :) Regards, Parth > On Jul 2, 6:29 pm, Parth wrote: > > > On Jul 3, 6:15 am, Parth wrote: > > > > Tom, Chouser, Thanks for your responses. > > > > As of now I am doing the same thing as suggested. > > > However, this tends be become painful the moment structures > > > start to nest. For e.g. I am using Clojure to decode a bit > > > of assembly and below is what I end up doing to see the > > > values of interest in hex: > > > > user=> (decode :b32 (nth test-ops 3)) > > > {:inst {:prefix (), :code (199 69 248 10 0 0 0), :op :movl, :args > > > [{:type :Ev-mem, :arg {:reg :ebp, :disp -8}} 10]}, :more ()} > > > user=> (def r (decode :b32 (nth test-ops 3))) > > > #'user/r > > > user=> (map hex (get-in r [:inst :code])) > > > ("c7" "45" "f8" "a" "0" "0" "0") > > > user=> (hex (second (get-in r [:inst :args]))) > > > "a" > > > user=> > > > > Basically, I need to extract each number seq or value > > > individually and print it in hex for every instruction I > > > decode and view. > > > > This isn't too much fun to do in the middle of a debug session :) > > > > Having something like *print-base* would be ideal IMHO > > > would make scenarios like this really easy as one could > > > simply do: > > > > user=> (set! *print-base* 16) > > > user=> (decode :b32 (nth test-ops 3)) > > > {:inst {:prefix (), :code (c7 47 f8 a 0 0 0), :op :movl, :args > > > [{:type :Ev-mem, :arg {:reg :ebp, :disp f8}} a]}, :more ()} > > > > In the absence of this I thought of writing a function > > > that would take an arbitrary Clojure structure/coll and print > > > it out in the manner like above. But then it won't > > > be much different from pprint with radix support but without > > > the pretty part. > > > > I suppose what I am hoping is that a feature request for > > > *print-base* sort of a mechanism get considered > > > for Clojure as it makes scenarios like the above very > > > easy to deal with. Any chance of this being somewhere > > > on the Clojue todo? :) > > > Rich, > > > If this is something you think would be a good addition > > to Clojure I could give a shot at creating a patch for > > this (with a CA of course). Please let me know. > > > I think rather than a generic radix support, if > > we have hex, bin and octal supported, most uses > > cases should be covered. > > > Regards, > > Parth > > > > I will probably create a poor mans radix based print > > > in the mean time for the this scenario. That should > > > be an interesting exercise. > > > > Thanks, > > > Parth > > > > On Jul 2, 10:58 pm, Chouser wrote: > > > > > On Thu, Jul 2, 2009 at 4:51 AM, Parth > > > > > Malwankar wrote: > > > > > > I frequently deal with hex and binary numbers. > > > > > As of now when I need to view a list of numbers > > > > > I just map a little hex function to it to translate it > > > > > into a list of hex strings at the repl. > > > > > > Having something like *print-base* / *print-radix* [1] may be > > > > > valuable in such a scenario > > > > > I don't think Java's built-in formatter is nearly as > > > > flexible as those, but getting hex or octal strings is easy > > > > enough: > > > > > user=> (format "%d" 255) > > > > "255" > > > > user=> (format "%o" 255) > > > > "377" > > > > user=> (format "%x" 255) > > > > "ff" > > > > user=> (format "%X" 255) > > > > "FF" > > > > > --Chouser --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: print-base / print-radix?
On Jul 3, 6:15 am, Parth wrote: > Tom, Chouser, Thanks for your responses. > > As of now I am doing the same thing as suggested. > However, this tends be become painful the moment structures > start to nest. For e.g. I am using Clojure to decode a bit > of assembly and below is what I end up doing to see the > values of interest in hex: > > user=> (decode :b32 (nth test-ops 3)) > {:inst {:prefix (), :code (199 69 248 10 0 0 0), :op :movl, :args > [{:type :Ev-mem, :arg {:reg :ebp, :disp -8}} 10]}, :more ()} > user=> (def r (decode :b32 (nth test-ops 3))) > #'user/r > user=> (map hex (get-in r [:inst :code])) > ("c7" "45" "f8" "a" "0" "0" "0") > user=> (hex (second (get-in r [:inst :args]))) > "a" > user=> > > Basically, I need to extract each number seq or value > individually and print it in hex for every instruction I > decode and view. > > This isn't too much fun to do in the middle of a debug session :) > > Having something like *print-base* would be ideal IMHO > would make scenarios like this really easy as one could > simply do: > > user=> (set! *print-base* 16) > user=> (decode :b32 (nth test-ops 3)) > {:inst {:prefix (), :code (c7 47 f8 a 0 0 0), :op :movl, :args > [{:type :Ev-mem, :arg {:reg :ebp, :disp f8}} a]}, :more ()} > > In the absence of this I thought of writing a function > that would take an arbitrary Clojure structure/coll and print > it out in the manner like above. But then it won't > be much different from pprint with radix support but without > the pretty part. > > I suppose what I am hoping is that a feature request for > *print-base* sort of a mechanism get considered > for Clojure as it makes scenarios like the above very > easy to deal with. Any chance of this being somewhere > on the Clojue todo? :) > Rich, If this is something you think would be a good addition to Clojure I could give a shot at creating a patch for this (with a CA of course). Please let me know. I think rather than a generic radix support, if we have hex, bin and octal supported, most uses cases should be covered. Regards, Parth > I will probably create a poor mans radix based print > in the mean time for the this scenario. That should > be an interesting exercise. > > Thanks, > Parth > > On Jul 2, 10:58 pm, Chouser wrote: > > > On Thu, Jul 2, 2009 at 4:51 AM, Parth > > > Malwankar wrote: > > > > I frequently deal with hex and binary numbers. > > > As of now when I need to view a list of numbers > > > I just map a little hex function to it to translate it > > > into a list of hex strings at the repl. > > > > Having something like *print-base* / *print-radix* [1] may be > > > valuable in such a scenario > > > I don't think Java's built-in formatter is nearly as > > flexible as those, but getting hex or octal strings is easy > > enough: > > > user=> (format "%d" 255) > > "255" > > user=> (format "%o" 255) > > "377" > > user=> (format "%x" 255) > > "ff" > > user=> (format "%X" 255) > > "FF" > > > --Chouser --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: print-base / print-radix?
On Jul 2, 9:44 pm, Tom Faulhaber wrote: > Hi Parth, > > It is on the agenda to support this for pprint, but I don't know > exactly when. > Thanks Tom. I look forward to this addition to the wonderful pprint function :) Regards, Parth > In the meantime, arbitrary bases *are* supported in the common lisp > compatible format function (cl-format) which is also part of > clojure.contrib.pprint. > > The interesting directives are ~X, ~B, and ~bR, where b is the base of > interest. For example, > > (cl-format nil "~X" 256) => "100" > > (cl-format nil "~12r" 256) => "194" > > (cl-format true "~{~X ~}~%" [2 4 8 16 32 64 128 256]) > > prints to *out*: > > 2 4 8 10 20 40 80 100 > > For all the dirt on using radix, look at the Common Lisp > Hyperspec:http://www.lispworks.com/documentation/HyperSpec/Body/22_cb.htm > > More info about the clojure implementation of format > here:http://code.google.com/p/clojure-contrib/wiki/CommonLispFormat(a > little out of date and about to be moved). > > HTH, > > Tom > On Jul 2, 1:51 am, Parth Malwankar wrote: > > > I frequently deal with hex and binary numbers. > > As of now when I need to view a list of numbers > > I just map a little hex function to it to translate it > > into a list of hex strings at the repl. > > > Having something like *print-base* / *print-radix* [1] may be > > valuable in such a scenario > > > Or maybe an enhanced pprint? Not sure if pprint already provides > > such an option or if its planned. > > > I would appreciate any comments or ideas if someone > > is doing something similar. > > > Thanks. > > Parth > > [1]http://www.lispworks.com/documentation/lw50/CLHS/Body/v_pr_bas.htm --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: print-base / print-radix?
Tom, Chouser, Thanks for your responses. As of now I am doing the same thing as suggested. However, this tends be become painful the moment structures start to nest. For e.g. I am using Clojure to decode a bit of assembly and below is what I end up doing to see the values of interest in hex: user=> (decode :b32 (nth test-ops 3)) {:inst {:prefix (), :code (199 69 248 10 0 0 0), :op :movl, :args [{:type :Ev-mem, :arg {:reg :ebp, :disp -8}} 10]}, :more ()} user=> (def r (decode :b32 (nth test-ops 3))) #'user/r user=> (map hex (get-in r [:inst :code])) ("c7" "45" "f8" "a" "0" "0" "0") user=> (hex (second (get-in r [:inst :args]))) "a" user=> Basically, I need to extract each number seq or value individually and print it in hex for every instruction I decode and view. This isn't too much fun to do in the middle of a debug session :) Having something like *print-base* would be ideal IMHO would make scenarios like this really easy as one could simply do: user=> (set! *print-base* 16) user=> (decode :b32 (nth test-ops 3)) {:inst {:prefix (), :code (c7 47 f8 a 0 0 0), :op :movl, :args [{:type :Ev-mem, :arg {:reg :ebp, :disp f8}} a]}, :more ()} In the absence of this I thought of writing a function that would take an arbitrary Clojure structure/coll and print it out in the manner like above. But then it won't be much different from pprint with radix support but without the pretty part. I suppose what I am hoping is that a feature request for *print-base* sort of a mechanism get considered for Clojure as it makes scenarios like the above very easy to deal with. Any chance of this being somewhere on the Clojue todo? :) I will probably create a poor mans radix based print in the mean time for the this scenario. That should be an interesting exercise. Thanks, Parth On Jul 2, 10:58 pm, Chouser wrote: > On Thu, Jul 2, 2009 at 4:51 AM, Parth > > Malwankar wrote: > > > I frequently deal with hex and binary numbers. > > As of now when I need to view a list of numbers > > I just map a little hex function to it to translate it > > into a list of hex strings at the repl. > > > Having something like *print-base* / *print-radix* [1] may be > > valuable in such a scenario > > I don't think Java's built-in formatter is nearly as > flexible as those, but getting hex or octal strings is easy > enough: > > user=> (format "%d" 255) > "255" > user=> (format "%o" 255) > "377" > user=> (format "%x" 255) > "ff" > user=> (format "%X" 255) > "FF" > > --Chouser --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
print-base / print-radix?
I frequently deal with hex and binary numbers. As of now when I need to view a list of numbers I just map a little hex function to it to translate it into a list of hex strings at the repl. Having something like *print-base* / *print-radix* [1] may be valuable in such a scenario Or maybe an enhanced pprint? Not sure if pprint already provides such an option or if its planned. I would appreciate any comments or ideas if someone is doing something similar. Thanks. Parth [1] http://www.lispworks.com/documentation/lw50/CLHS/Body/v_pr_bas.htm --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: Hash Consing
On Jun 29, 3:09 pm, Nicolas Oury wrote: > Dear all, > > I am coding a (very) small hash consing library for clojure. > > For those we don't happen to know what hash consing is, it is a way of > allowing equal data structures to be shared in memory. > This leverages the purity (as in "immutability") of data structures to > reduce memory footprint (no duplication of data for just a constant > overhead per allocation) and makes hashing and equality tests faster. > (You can use java non overloaded hashCode, and == to test equality, > because of the sharing. So both operations are O(1), with a very small > constant, whatever is the complexity of the hash consed data > structures.) I don't know anything about hash consing. Based on my limited understanding of the description I am just wondering if this is different from structural sharing that Clojure collections have. Quoting the docs[1]: " In particular, the Clojure collections support efficient creation of 'modified' versions, by utilizing structural sharing, and make all of their performance bound guarantees for persistent use. " Do you have something different in mind with hash consing? Regards, Parth [1] http://clojure.org/data_structures#toc12 > This can then be used, in combination with referential transparency to > make memoized function faster. > > I have a java file and a clojure interface that seem to work, at least > on my example. I plan to put something somewhere someday, but before > spending too much time in making this releasable, i Have a few > questions: > > - does something already exists in contrib that I have missed? > - is someone else working on that? > - are there any "features that I need and that you must implement" that > you think of? > > My current plans are: > - using a java concurrent hash map to soft referenced objects for the > hash consing table. > - only two fields in an hash consed object: the value it represents, > and a generic field called "cached_data" used to store anything you > want to memoize about this data structure. (Keeping this cached data a > bit longer is the reason I plan to use soft references and not weak > references) > > I am not a clojure expert and I am not a java coder at all, so don't > hesitate to tell me if my plans are somehow wrong. > > Bets regards, > > Nicolas. --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: accum
On Jun 17, 10:24 am, Wrexsoul wrote: > On Jun 17, 12:44 am, Daniel Lyons wrote: > > > > (use 'clojure.contrib.seq-utils) > > Don't have that library. Still hasn't been released yet, last I > checked. I am not sure if a pre-built clojure-contrib.jar is available. You could consider building from sources. It should be quite straightforward. [src]% git clone git://github.com/richhickey/clojure-contrib.git [src]% cd clojure-contrib [clojure-contrib]% ant clean jar -Dclojure.jar=../clojure/clojure.jar [clojure-contrib]% ls build.xml classes/ ClojureCLR/ clojure-contrib.jar clojure-contrib- slim.jar clojurescript/ CPL.TXT* epl-v10.html launchers/ pom.xml README.txt Revisions src/ [clojure-contrib]% Note that -Dclojure.jar in the ant command above should point to whereever you have the clojure.jar. clojure-contrib has a lot of useful libs that you will miss out on in case you are not using it. Regards, Parth --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: accum
On Jun 17, 9:34 am, Wrexsoul wrote: > I'm shocked that this is missing from clojure.core: > > (defn accum [f init coll] > (loop [x init c coll] > (if (empty? c) > x > (recur (f x (first c)) (rest c) > > user=> (accum + 0 [1 2 3]) > 6 > user=> (accum + 0 [1 2 3 4 5]) > 15 > > This is one of the most basic, useful functions in functional > programming. :) > > Here's any triangular number: > > (defn tri [n] (accum + 0 (take n (iterate inc 1 > Maybe "apply" can be used user=> (apply + [1 2 3]) 6 user=> (apply + [1 2 3 4 5]) 15 user=> (defn tri [n] (accum + 0 (take n (iterate inc 1 #'user/tri user=> (tri 10) 55 user=> (def inf (iterate inc 1)) #'user/inf user=> (defn tri2 [n] (apply + (take n inf))) #'user/tri2 user=> (tri2 10) 55 user=> or "reduce"? user=> (reduce + 0 [1 2 3]) 6 user=> (reduce + 10 [1 2 3]) 16 user=> (reduce + 0 [1 2 3 4 5]) 15 Regards, Parth > Here's a lazy seq of them all: > > (def *tris* (for [i (iterate inc 1)] (tri i))) > > This, however, is more efficient (and demonstrates another case where > super-lazy-seq makes something very compact and readable): > > (defn accum-map [f init coll] > (super-lazy-seq [x init c coll] > (if (seq c) > (next-item x (f x (first c)) (rest c) > > (def *tris* (rest (accum-map + 0 (iterate inc 1 > > Notice how similar the accum-map code is to the accum code? With just > lazy-seq it would not be as clear. :) > > The "rest" in the replacement def for *tris* is because accum-map > returns the init value as the first value of the sequence, i.e., it's > equivalent to making a sequence of (tri 0), (tri 1), (tri 2), and so > on. --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: matlab like clojure
On Jun 15, 7:23 pm, Bugs wrote: > Hi, everyone. > > I'm a newbie on Clojure and LISP, and I'm interasted in matlab > replacement languages. > It is just my hobby, but I'm trying to implement a matlab like > language extension. > > I think that Clojure has ability enough to be numerical language like > a Matlab or Mathematica. > > So, I'm finding examples for matrix operation ( + - * .* > transpose ./ .^, and so on) > > Does anyone have the examples? > I don't know much about matlab or mathematica but you might find incanter interesting. http://github.com/liebke/incanter/tree/master Regards, Parth > Regards, --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: Dynamically accessing static fields
On Jun 15, 7:08 am, James Koppel wrote: > I am trying to write a function to simplify working with GridBagConstraints > -- that is, instead of writing > > (let [c (GridBagConstraints.)] > (set! (.weightx c) 2.0) > (set! (.gridwidth c) GridBagConstraints/REMAINDER) > (let [button (JButton. "Hello, world!")] > (.setConstraints (.getLayout *my-container*) button c) > (.add *my-container* button))) > > I could simply write > > (gridbag-add *my-container* > (JButton. "Hello, world!") > "weightx=2.0;gridwith=GridBagConstraints/REMAINDER") > > A simple combination of regexes and read-string would easily allow me to > extract the symbol 'GridBagConstraints/REMAINDER from the example string, > but I'm having trouble actually converting it into its value. Using resolve > simply returns nil, and getting "." to work dynamically seems to be > fruitless, as even this simple call > > (. (resolve 'GridBagConstraints) REMAINDER) > > throws an exception. > > So, the question is, how do I go dynamically from a string like > "GridBagConstraints/REMAINDER" to the actual value of the static field? > > Of course, eval does the trick, but I'd rather not have to resort to it. One way to do that would be to use a map: user=> (def m {"Math/PI" Math/PI "Math/E" Math/E}) #'user/m user=> (defn foo [n s] [n (get m s :not-found)]) #'user/foo user=> (foo 10 "Math/PI") [10 3.141592653589793] user=> You could also consider writing a function that takes these as parameters and returns the updated container. That way you can avoid the regex. Regards, Parth > > Sorry if the answer is obvious; I'm a Clojure-newbie. --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: Performance Penalty Converting from Java Code
On Jun 14, 7:00 pm, tmountain wrote: > I've been playing around with rewriting some Java code in Clojure and > did some simple benchmarking in the process. In this case, there's a > huge disparity in the performance numbers between the two languages, > and I'm wondering what the cause may be. The program rotates a string > from "", "aaab", ..., "". The Java version takes 0.77 seconds > to complete while the Clojure version takes 22 seconds. I've tried to > make the scripts relatively isomorphic and have verified that they > produce the same results. I'm pasting the source below. > Here is a clojure version that runs significantly faster on my system. The main optimizations I have done are coercion to primitives and using unchecked ops. As I understand it, the original clojure version is slow because its safer (checks for overflows etc.). (defn xbase26 [n] (let [seed-string "" s (new StringBuilder seed-string) a_val (int \a)] (loop [pos 3 x (int n)] (when (pos? x) (let [digit (char (+ a_val (unchecked-remainder x 26)))] (.setCharAt s pos digit) (when (pos? pos) (recur (int (dec pos)) (unchecked-divide x 26)) (.toString s))) These are the numbers I see: ;; java [clojure]% time java -cp . Base26 java -cp . Base26 0.40s user 0.02s system 88% cpu 0.476 total ;; original [clojure]% time java -cp .:classes:/home/parthm/src/clojure/ clojure.jar base26 java -cp .:classes:/home/parthm/src/clojure/clojure.jar base26 33.08s user 1.18s system 99% cpu 34.456 total [clojure]% ;; optimized [clojure]% time java -cp .:classes:/home/parthm/src/clojure/ clojure.jar base26 java -cp .:classes:/home/parthm/src/clojure/clojure.jar base26 1.75s user 0.11s system 104% cpu 1.784 total While this works well, I more optimization may be possible by choosing an algorithm thats more suited and ideomatic for clojure. I suppose that intent here is to do a micro-benchmark. Regards, Parth > tra...@travis-ubuntu:/tmp% time clj base26.clj > clj base26.clj 21.99s user 1.23s system 85% cpu 27.318 total > > tra...@travis-ubuntu:/tmp% time java Base26 > java Base26 0.77s user 0.04s system 78% cpu 1.029 total > > clojure version: > > (defn base26 [n] > (let [seed-string "" > s (new StringBuilder seed-string)] > (loop [pos (- (count seed-string) 1) > x n] > (if (> x 0) > (let [digit (+ (int \a) (mod x 26))] > (. s setCharAt pos (char digit)) > (if (and (> pos 0) (> x 0)) > (recur (- pos 1) (/ x 26)) > (. s toString))) > > (doseq [i (range (Math/pow 26 4))] > (base26 i)) > > java version: > > import java.lang.StringBuilder; > > public class Base26 { > public static void main(String[] args) { > for (int i = 0; i < Math.pow(26, 4); i++) { > Base26.base26(i); > } > } > > public static String base26(int num) { > if (num < 0) { > throw new IllegalArgumentException("Only positive numbers > are supported"); > } > StringBuilder s = new StringBuilder(""); > for (int pos = 3; pos >= 0 && num > 0 ; pos--) { > char digit = (char) ('a' + num % 26); > s.setCharAt(pos, digit); > num = num / 26; > } > return s.toString(); > } > > } > > I've tried warn-on-reflection, and it didn't report anything. > > Thanks, > Travis --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: macro escapes and passing method names are function arguments
On Jun 9, 11:50 am, Josh Smith wrote: > I've been trying to understand the macro syntax in clojure. I think > macro's are closer to the kind of functionality I'm looking for (as > opposed to multi-methods) but I'm not sure. > > http://gist.github.com/126315 > Hi Josh, As a general recommendation, its better to use functions instead of macros as functions provide a lot of flexibility (e.g. you can apply them). The thumb rule I use to use a macro only if I can't do something with a function. user=> (defmacro double-mac [x] `(* ~x ~x)) #'user/double-mac user=> (double-mac 2) 4 user=> (defn double-fn [x] (* x x)) #'user/double-fn user=> (map double-fn [1 2 3]) (1 4 9) user=> (map double-mac [1 2 3]) java.lang.Exception: Can't take value of a macro: #'user/double-mac (NO_SOURCE_FILE:8) user=> Another minor comment, Lisp style programming usually stacks up parenthesis at the end rather than put them in separate lines like C or Java. E.g. (defn foo [coll] (map inc coll)) rather than (defn foo [coll] (map inc coll) ) > I wrote the above code, which simply processes Java-style Properties > files (using the java interfaces) as > a learning exercise. It works, but I'm still hazy about exactly why > it works. > I don't know java too well so I can't really talk much about properties file. :( There are some functions dealing with properties in clojure.contrib.java-utils. They might be good for use/reference in case you haven't seen them already. http://code.google.com/p/clojure-contrib/wiki/JavaUtilsApiDoc > I spent a lot of time figuring out the escape/not escape syntax. What > do you recommend as a starting place for understanding what needs to > be escaped, and what doesn't? Is that even the right question? > What's the best way to learn the proper care and feeding of macros? > Is there another/better way of passing a method name to a function as > an argument than via a macro? > I found PCL and OnLisp very useful to understand macros. http://gigamonkeys.com/book/ http://www.paulgraham.com/onlisp.html Both are available online. You could just look at the chapters relevant to macros. Though these books deal with Common Lisp the same principles hold and the macro system is similar (in clojure you don't need gensym as often). > Another question I have is that the Properties class is listed as > being thread safe. Does that mean > it can safely be used in the multi-threaded Clojure app? > > Lastly, is there any way to turn a string into a :thing? For > example, I've got "stow" and I want a function > that returns :stow. > The :thing are called keywords in Lisp/Clojure and are very useful. I think what you are looking for is: user=> (keyword "stow") :stow Regards, Parth > Thank you --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: Threadring Benchmark
So I got a chance to do some tweaks to the clojure code and run the benchmark. I also used the "approved" (not alternative) version of java code for comparison. I must say I am impressed with the clojure agent performance. The previous implementation results for 20,000,000 hops was: java: 27.14 sec, 92% cpu scala: 190.78 sec, 183% cpu clojure: 215.26 sec, 134% cpu The new results are: java: 33.56 sec, 94% cpu scala: 191.08 sec, 177% cpu clojure: 77.01 sec, 91% cpu The tweaks to clojure code were minor. Basically, coercing hops to (int hops) and using (neg? hops) instead of =. Detailed Log: http://gist.github.com/125614 Updated Clojure Code: http://gist.github.com/125615 Jave Code: http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&lang=java&id=4 Scala Code: http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&lang=scala&id=1 Regards, Parth On Jun 6, 2:39 pm, Parth wrote: > On Jun 6, 11:44 am, Sean Devlin wrote: > > > This problem came up on the mailing list recently: > > >http://groups.google.com/group/clojure/browse_thread/thread/5e0c078d0... > > > You might want to compare your code to what was done here, but at a > > glance the implementations are similar. > > > You provide relative speed comparisons (Such and such is % > > better...). Would you be able to share absolute times as well? I'm > > just curious at this point. > > > Sean > > For some reason the google spreadsheet link provided in > my original mail requires users to login for viewing. > The same numbers are available in this published > google spreadsheet (hopefully without login). > > http://tinyurl.com/ofhync > > Regards, > Parth > > > > > On Jun 6, 12:41 am, Parth Malwankar wrote: > > > > Hello, > > > > In order to understand the agent model of Clojure > > > better I wrote the alioth shootout threadring benchmark [1]. > > > I ran some tests to compare it with the Java and Scala > > > implementation [2, 3] which I picked from the published > > > benchmarks. > > > > The clojure code can be found here:http://gist.github.com/124688 > > > > The benchmark from my two core 1.7GHz pentium system > > > (ubuntu 9.04) w/ 1GB RAM can be found > > > here:http://spreadsheets.google.com/ccc?key=rQLD6jgTTV5OqXwHdXtrTyg > > > > In summary, scala implementation is 6.34x times slower than > > > java, clojure is 7.8x. Avg CPU consumption is 93.3% for java and > > > 179.2% and 131.34% for scala and clojure respectively. > > > > I thought of sharing this in case others are interested. > > > As this is my first program using clojure agents I would appreciate > > > any > > > comments on improving the Clojure implementation (or in case > > > there are any bugs). > > > > Thanks. > > > Parth > > > PS: For the Java implementation I happen to pick the "interesting > > > alternate programs" (Java 6 -server #5) but it was already quite > > > late in the cycle when I realized that. So the Java numbers are > > > probably better than the other java implementations. > > > > [1]http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&;... > > > [2]http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&;... > > > [3]http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&;... --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: Threadring Benchmark
On Jun 6, 11:44 am, Sean Devlin wrote: > This problem came up on the mailing list recently: > > http://groups.google.com/group/clojure/browse_thread/thread/5e0c078d0... > > You might want to compare your code to what was done here, but at a > glance the implementations are similar. > > You provide relative speed comparisons (Such and such is % > better...). Would you be able to share absolute times as well? I'm > just curious at this point. > > Sean For some reason the google spreadsheet link provided in my original mail requires users to login for viewing. The same numbers are available in this published google spreadsheet (hopefully without login). http://tinyurl.com/ofhync Regards, Parth > > On Jun 6, 12:41 am, Parth Malwankar wrote: > > > Hello, > > > In order to understand the agent model of Clojure > > better I wrote the alioth shootout threadring benchmark [1]. > > I ran some tests to compare it with the Java and Scala > > implementation [2, 3] which I picked from the published > > benchmarks. > > > The clojure code can be found here:http://gist.github.com/124688 > > > The benchmark from my two core 1.7GHz pentium system > > (ubuntu 9.04) w/ 1GB RAM can be found > > here:http://spreadsheets.google.com/ccc?key=rQLD6jgTTV5OqXwHdXtrTyg > > > In summary, scala implementation is 6.34x times slower than > > java, clojure is 7.8x. Avg CPU consumption is 93.3% for java and > > 179.2% and 131.34% for scala and clojure respectively. > > > I thought of sharing this in case others are interested. > > As this is my first program using clojure agents I would appreciate > > any > > comments on improving the Clojure implementation (or in case > > there are any bugs). > > > Thanks. > > Parth > > PS: For the Java implementation I happen to pick the "interesting > > alternate programs" (Java 6 -server #5) but it was already quite > > late in the cycle when I realized that. So the Java numbers are > > probably better than the other java implementations. > > > [1]http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&;... > > [2]http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&;... > > [3]http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&;... --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Threadring Benchmark
Hello, In order to understand the agent model of Clojure better I wrote the alioth shootout threadring benchmark [1]. I ran some tests to compare it with the Java and Scala implementation [2, 3] which I picked from the published benchmarks. The clojure code can be found here: http://gist.github.com/124688 The benchmark from my two core 1.7GHz pentium system (ubuntu 9.04) w/ 1GB RAM can be found here: http://spreadsheets.google.com/ccc?key=rQLD6jgTTV5OqXwHdXtrTyg In summary, scala implementation is 6.34x times slower than java, clojure is 7.8x. Avg CPU consumption is 93.3% for java and 179.2% and 131.34% for scala and clojure respectively. I thought of sharing this in case others are interested. As this is my first program using clojure agents I would appreciate any comments on improving the Clojure implementation (or in case there are any bugs). Thanks. Parth PS: For the Java implementation I happen to pick the "interesting alternate programs" (Java 6 -server #5) but it was already quite late in the cycle when I realized that. So the Java numbers are probably better than the other java implementations. [1] http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&lang=all [2] http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&lang=java&id=5 [3] http://shootout.alioth.debian.org/u32q/benchmark.php?test=threadring&lang=scala&id=1 --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Re: AIML pattern matcher design
On Fri, 08 May 2009 22:20:13 +0530, dhs827 wrote: > > > ; First thing to learn is XML parsing with Clojure. > > > Other comments, tips, disses? > > Dirk In case you don't expect end users or other languages to access the configuration, one option you have is to save the configuration directly as Clojure data. As Clojure is a lisp, you have access to the reader and you could read the data (maps, vectors, etc.) directly from the file. E.g.: user=> (def x (read-string "{:a 1 :b 2}")) #'user/x user=> x {:a 1, :b 2} user=> See also: (doc read) If you decide to go ahead with xml, you can use the xml support in clojure core: http://clojure.org/api#toc673 Regards, Parth --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: What's the function that returns the opposite of a predicate?
On Thu, 30 Apr 2009 23:20:14 +0530, samppi wrote: > > I know there's a core function that takes a predicate and returns its > opposite: > > (defn mystery [predicate] > (fn [x] (not (predicate x > > I'm having a lot of trouble finding the name of it in the docs, > though. Could anyone give me its name? Or does this function not exist > in the core? user=> (doc complement) - clojure.core/complement ([f]) Takes a fn f and returns a fn that takes the same arguments as f, has the same effects, if any, and returns the opposite truth value. nil user=> Regards, Parth --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: new in duck-streams: with-out-writer / with-in-reader
On Mar 29, 7:36 am, Stuart Sierra wrote: > Following a discussion from a few days ago, I've added two new macros > to clojure.contrib.duck-streams: > > (defmacro with-out-writer > "Opens a writer on f, binds it to *out*, and evalutes body." > [f & body] > `(with-open [stream# (writer ~f)] > (binding [*out* stream#] > �...@body))) > > (defmacro with-in-reader > "Opens a PushbackReader on f, binds it to *in*, and evaluates body." > [f & body] > `(with-open [stream# (PushbackReader. (reader ~f))] > (binding [*in* stream#] > �...@body))) > > -Stuart Sierra This is very useful. Thank you :) --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: exposing specific functions via namespace
On Mar 26, 8:35 am, "John D. Hume" wrote: > On Wed, Mar 25, 2009 at 12:05 PM, Parth wrote: > > I have split up the foo namespace across multiple files. So, > > I have the following now: > > > src/org/ppm/foo.clj -> org.ppm.foo > > src/org/ppm/bar.clj -> org.ppm.foo > > src/org/ppm/baz.clj -> org.ppm.foo > > > With foo.clj using the ns :load for loading bar and baz. > > > (ns org.ppm.foo > > (:load "bar" "baz")) > > > This meets my needs well as the code is split in > > logical units while exposing the same namespace > > to the end user. > > You may want to take a look at > compojure.ns-utils/immigrate.http://github.com/weavejester/compojure/tree/master > It just creates public vars pointing at all the public vars in the > source namespace. > > -hume. > --http://elhumidor.blogspot.com/ Thats a neat way to do it. Thanks for pointing it out. Parth --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: exposing specific functions via namespace
On Mar 25, 7:04 pm, Parth Malwankar wrote: > Hello, > > I am trying to organise my code in namespaces and needed a > little help. > > Basically I have created the following namespaces similar to > the following: > > src/org/ppm/foo.clj -> org.ppm.foo > src/org/ppm/foo/ > src/org/ppm/foo/bar.clj -> org.ppm.foo.bar > src/org/ppm/foo/baz.clj -> org.ppm.foo.baz > > foo.clj is an empty file which does nothing but > combines bar and baz: > > == foo.clj == > (ns org.ppm.foo > (:use [org.ppm.foo bar baz])) > > After having the jar in classpath, I create a simple > test.clj script that I load. > > == test.clj == > (use 'org.ppm.foo) > (bar-func) > (baz-func) > > At this point, test.clj does not see the functions > defined in bar and baz. > Doing a (in-ns 'org.ppm.foo) before function calls > makes it work fine. > > Is there a way to have foo.clj selectively (or all) expose > functions from bar and baz to the end user via foo namespace? > > Do I need to put all exposed functions into foo.clj? I would > prefer to keep them in bar and baz if possible as those > are logical blocks for me. Sorry for replying to my own post. I think I figured out one way of meeting my needs. I have split up the foo namespace across multiple files. So, I have the following now: src/org/ppm/foo.clj -> org.ppm.foo src/org/ppm/bar.clj -> org.ppm.foo src/org/ppm/baz.clj -> org.ppm.foo With foo.clj using the ns :load for loading bar and baz. (ns org.ppm.foo (:load "bar" "baz")) This meets my needs well as the code is split in logical units while exposing the same namespace to the end user. Parth > > Thanks. > Parth --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
exposing specific functions via namespace
Hello, I am trying to organise my code in namespaces and needed a little help. Basically I have created the following namespaces similar to the following: src/org/ppm/foo.clj -> org.ppm.foo src/org/ppm/foo/ src/org/ppm/foo/bar.clj -> org.ppm.foo.bar src/org/ppm/foo/baz.clj -> org.ppm.foo.baz foo.clj is an empty file which does nothing but combines bar and baz: == foo.clj == (ns org.ppm.foo (:use [org.ppm.foo bar baz])) After having the jar in classpath, I create a simple test.clj script that I load. == test.clj == (use 'org.ppm.foo) (bar-func) (baz-func) At this point, test.clj does not see the functions defined in bar and baz. Doing a (in-ns 'org.ppm.foo) before function calls makes it work fine. Is there a way to have foo.clj selectively (or all) expose functions from bar and baz to the end user via foo namespace? Do I need to put all exposed functions into foo.clj? I would prefer to keep them in bar and baz if possible as those are logical blocks for me. Thanks. Parth --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: file io
On Mar 24, 11:53 pm, e wrote: > does anyone else think that should be more fundamental like the python > example? imagine saying that out loud to your friend who asks . . . and the > amount of noise, visually: > > "use clojure dot contrib dot duck dash streams". > > perhaps it is already the hope that it will "spit" will eventually sit next > to "slurp"? > This has come up before on the list. I am not sure about where things stand with that though. http://groups.google.com/group/clojure/browse_thread/thread/31f01808c225ecc1/d0e286fa0c8ef7d2 http://groups.google.com/group/clojure/browse_thread/thread/d8064dbb94c5cd2c/ba355cfe2c708068 I think it would be nice to have "spit" in the core, especially for people like me who aren't too good with java. But having clojure-contrib.duck-streams definately makes life easier :) Parth --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: file io
e wrote: > is there something as simple as this in clojure? > > whole python program: > > of = open(filename,"w") > of.write("hello") > of.close() > > I checked the api and looked around the wiki and google quickly and saw how > to use java's stuff to do it ... but, welll... > There are possibly other (better) ways to do it. One way is: user=> (use 'clojure.contrib.duck-streams) nil user=> (with-open [f (writer (file "test.txt"))] (binding [*out* f] (println "hello world !!!"))) nil user=> % cat test.txt hello world !!! % clojure.contrib.duck-stream has an interesting set of functions. Parth > I noticed "slurp" in the api for reading ... but only the whole file at once > (read() but no readline()). Is there something symmetrical for writing > (outputting)? Is there a web page called "File IO" somewhere? > > Thanks. --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
arbitrary partitioning of collection
Hello, I have a use case for reading binary data from a file into a C equivalent structure. I read the binary date into a byte array before processing. I came up with a split-byte-array function for this: (defn split-byte-array "takes a byte-array and returns its various fields as a list of sequences. the length of each field in bytes is taken from the list lens user=> (split-byte-array (range 10) [3 2 2 3]) [(0 1 2) (3 4) (5 6) (7 8 9)]" ([byte-array lens] (split-byte-array byte-array lens [])) ([byte-array lens acc] (if (empty? lens) acc (let [[s r] (split-at (first lens) byte-array)] (recur r (rest lens) (conj acc s)) As shown in documentation for the function, the stream gets split up into 3 2 2 and 3 bytes in the above case. I was wondering if there is a better way to do this. This reminds me of "partition" but that doesn't support something like a vector of partition sizes. This is a common use case for a handling a binary dump of c structures. Is there any better way to do it than above? Is this a common enough case to have something like (partition coll ns) in contrib or core? Parth --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
dot and nums in keywords
Hello, As per the docs for keywords ( http://clojure.org/reader ), keywords cannot contain '.'. "They cannot contain '.' or name classes." However, the following works on the repl: user=> :.. :.. user=> (keyword? :..) true Are '.'s allowed and the docs need updating? Or should we see an exception? Also, would a keyword with only numbers be a valid keyword? e.g. : Thanks. Parth --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: How to encapsulate local state in closures
On Dec 22, 12:25 pm, "Mark Engelberg" wrote: > I misspoke; it's the call to counter that's the problem. Let's say > you want to use a counter to count the number of times a ref is set, > something like this: > > (dosync (counter) (ref-set r 1)) > > If your var-set causes the transaction to retry, an atom-based counter > will increment twice. As I understand it, atoms are one of the most > "dangerous" things in Clojure, and should be avoided unless you're > completely sure it will not change the semantics of your program if it > gets executed multiple times. Aside from the memoization example for > which it was invented, I am hard-pressed to think of a good use for > atoms. For something like a counter, you really have to use ref, and > that should remain people's default when dealing with mutability. > > I haven't done much with atoms yet, so if I've misunderstood Rich's > posts, feel free to explain my mistake. Thats a valid example. "counter" should not be used in the dosync. However, if the counter is meant for a single thread then one way to use it would be: ... (counter) (dosync (ref-set r 1)) ... Basically, as counter has side-effects it shouldn't be called in dosync as stated in the docs ( http://clojure.org/refs ) To quote the docs: 7. I/O and other activities with side-effects should be avoided in transactions, since transactions will be retried. The io! macro can be used to prevent the use of an impure function in a transaction. End quote. The above is a general rule so for e.g. we should not have (dosync (println "done setting") (ref-set r 1)). If my understanding is correct, this should be: ... (println "done setting") (dosync (ref-set r 1)) ... If we want a counter to count events across multiple threads, then yes, it would make sense to use refs. If I get it right, atoms are quite useful to maintain state in the context of a single thread with memoization and counter (within a thread) being two examples. There may possibly be performance implications for refs and atoms but I haven't really benchmarked it. Parth --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: How to encapsulate local state in closures
On Dec 22, 5:45 am, "Mark Engelberg" wrote: > But if mk-counter is called twice because it's retried in part of a > transaction, then you're in big trouble when you use atom. Better to > use a ref here. atom needs to be reserved for the very few cases when > retries don't matter (like a cache). If I understand it right, as long as the "counter" is used within a single thread and not across threads there shouldn't be any issues. Same as a cache. If the idea is to use one counter across multiple threads then refs can be used. I don't think I follow why mk-counter would be retried. There is not reason for it to fail as it simply creates a new "counter" and returns it and doesn't need to block or be blocked. Parth --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: How to encapsulate local state in closures
On Dec 22, 5:24 am, "Brian Doyle" wrote: > I haven't been following the new atom stuff, so I was wondering why atom > would be best in this > situation, vs a ref? Thanks. Rich discusses the use of atoms, refs and agents in good detail in this thread: http://groups.google.com/group/clojure/msg/fd0371eb7238e933 In case you don't want multiple counters but just one, the following can also be done. user=> (let [n (atom 0)] (defn counter [] (swap! n inc))) #'user/counter user=> (counter) 1 user=> (counter) 2 user=> (counter) 3 Parth > > On Sun, Dec 21, 2008 at 1:03 PM, Parth Malwankar > wrote: > > > > > On Dec 21, 11:47 pm, chris wrote: > > > I would like to be able to encapsulate local state in a closure. > > > Specifically, I would like a function that returns an incrementing > > > integer, thus: > > > (test_func) > > > 1 > > > (test_func) > > > 2 > > > What is the best way to go about this? With local bindings is failing > > > and I can't figure just why... > > > One way to do this would be to use atom. > > > (defn mk-counter [start] > > (let [n (atom start)] > > (fn [] (swap! n inc > > > (def counter (mk-counter 0)) > > > user=> (counter) > > 1 > > user=> (counter) > > 2 > > user=> (counter) > > 3 > > > Parth > > > (def test_closure > > > (with-local-vars [one 1] > > > (fn [] (var-get one > > > #'user/test_closure > > > user> (test_closure) > > > ; Evaluation aborted. > > > The var is null when I call the closure. > > > > Thanks, > > > Chris --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: clojure.lang.Script
On Dec 21, 8:21 pm, Emeka wrote: > > java -cp clojure.jar clojure.lang.Script yourapp.clj > > In my SciTe I added java -cp clojure.jar clojure.lang.Script $(FilePath) > plus others and when I click 'GO' or F5 instead of running the code and > printing result. I have > > > > > java -cp clojure.jar clojure.lang.Script C:\janus\myapp.clj > > exit 0 > > No other thing comes out. So how do I cause it to print the result of the > code I have written. It works in SciTe, however, it doesn't print result. > Have you used clojure.Lang.Script with SciTe before? If you are using the latest Clojure you can probably try: java -cp clojure.jar clojure.main filename.clj I haven't used SciTe but this is what I do in my clojure launch script. Parth > > Emeka. --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: How to encapsulate local state in closures
On Dec 21, 11:47 pm, chris wrote: > I would like to be able to encapsulate local state in a closure. > Specifically, I would like a function that returns an incrementing > integer, thus: > (test_func) > 1 > (test_func) > 2 > What is the best way to go about this? With local bindings is failing > and I can't figure just why... > One way to do this would be to use atom. (defn mk-counter [start] (let [n (atom start)] (fn [] (swap! n inc (def counter (mk-counter 0)) user=> (counter) 1 user=> (counter) 2 user=> (counter) 3 Parth > (def test_closure > (with-local-vars [one 1] > (fn [] (var-get one > #'user/test_closure > user> (test_closure) > ; Evaluation aborted. > The var is null when I call the closure. > > Thanks, > Chris --~--~-~--~~~---~--~~ 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 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 -~--~~~~--~~--~--~---
Re: recur vs. lazy: establishing guidelines
On Dec 9, 11:18 pm, Stuart Halloway <[EMAIL PROTECTED]> wrote: > Hi all, > > I am working on the functional programming chapter for the book this > week, and I have been reviewing uses of loop/recur vs. lazy-cat/lazy- > cons in Clojure to come up with some guidelines. > > Here is where I am: If your function creates/returns only atoms or > fixed size collections, loop/recur is fine. If it might return (or > internally create) variable/huge/infinite collections, use lazy-*. > > To make this more concrete: If you buy these guidelines, then butlast > is incorrect. If you point it at something huge it consumes all of > memory: > > (last (butlast (take 1 (iterate inc 0 > -> java.lang.OutOfMemoryError: Java heap space > > A lazy version works just fine: > > (defn lazy-butlast [s] > (if (rest s) > (lazy-cons (first s) (allbutlast (rest s))) > nil)) > > (last (lazy-butlast (take 1 (iterate inc 0 > -> 9998 > > But I bet that isn't the whole story. What are the counterarguments in > favor of non-lazy butlast? > > Cheers, > Stuart I am assuming 'allbutlast' is 'lazy-butlast'. Not really an in favor of butlast, but lazy-butlast also seems much faster. user=> (time (last (butlast (take 100 (iterate inc 0) "Elapsed time: 2710.068764 msecs" 98 user=> (time (last (lazy-butlast (take 100 (iterate inc 0) "Elapsed time: 714.63721 msecs" 98 user=> (time (last (butlast (take 100 (iterate inc 0) "Elapsed time: 1832.329244 msecs" 98 user=> (time (last (lazy-butlast (take 100 (iterate inc 0) "Elapsed time: 710.971437 msecs" 98 user=> (time (last (butlast (take 100 (iterate inc 0) "Elapsed time: 1266.704242 msecs" 98 user=> (time (last (lazy-butlast (take 100 (iterate inc 0) "Elapsed time: 701.681986 msecs" 98 user=> (time (last (butlast (take 100 (iterate inc 0) "Elapsed time: 1712.931529 msecs" 98 user=> (time (last (lazy-butlast (take 100 (iterate inc 0) "Elapsed time: 694.106062 msecs" 98 user=> Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Noob question on strings.
On Dec 9, 4:47 pm, Ant <[EMAIL PROTECTED]> wrote: > Hi all, > > I've just started looking with interest at the language, and have > decided to port some of my smaller programs and scripts to Clojure as > a way of getting to know the language. I am stumbling over Strings at > the moment, as I am trying to read a file. I have tried the following: > > user=> "C:\dev\java\clojure\clj-repl.bat" > ")\n" > user=> java.lang.Exception: Invalid token: C: > java.lang.Exception: ReaderError:(8,1) Invalid token: C: > at clojure.lang.LispReader.read(LispReader.java:164) > at clojure.lang.Repl.main(Repl.java:68) > Caused by: java.lang.Exception: Invalid token: C: > at clojure.lang.LispReader.interpretToken(LispReader.java:266) > at clojure.lang.LispReader.read(LispReader.java:156) > ... 1 more > > OK, so that didn't work. I read the docs on Strings: > > Strings - Enclosed in "double quotes". May span multiple lines. > Standard Java escape characters are supported. > > So next I tried, thinking it may be the backslashes that were the > problem, and needed escaping: > > "C:\\dev\\java\\clojure\\clj-repl.bat" > "\n" > user=> java.lang.Exception: Invalid token: C: Seems to work for me (on Linux with svn HEAD): user=> "C:\\dev\\java\\clojure\\clj-repl.bat" "C:\\dev\\java\\clojure\\clj-repl.bat" user=> "C:/dev/java/clojure/clj-repl.bat" "C:/dev/java/clojure/clj-repl.bat" user=> "C:" "C:" What release are you using? I am assuming you are on windows based on the string. Maybe you can try with the latest svn sources. Parth > java.lang.Exception: ReaderError:(10,1) Invalid token: C: > at clojure.lang.LispReader.read(LispReader.java:164) > at clojure.lang.Repl.main(Repl.java:68) > Caused by: java.lang.Exception: Invalid token: C: > at clojure.lang.LispReader.interpretToken(LispReader.java:266) > at clojure.lang.LispReader.read(LispReader.java:156) > ... 1 more > > Same error, and it seems to me that the double quoted string isn't > being accepted as a string literal. I tried converting the path to > forward slashes: > > java.lang.Exception: No such namespace: C:/dev/java/clojure > clojure.lang.Compiler$CompilerException: NO_SOURCE_FILE:0: No such > namespace: C:/dev/java/clojure > at clojure.lang.Compiler.analyze(Compiler.java:3713) > at clojure.lang.Compiler.analyze(Compiler.java:3671) > at clojure.lang.Compiler.eval(Compiler.java:3895) > at clojure.lang.Repl.main(Repl.java:75) > Caused by: java.lang.Exception: No such namespace: C:/dev/java/clojure > at clojure.lang.Compiler.resolveIn(Compiler.java:3998) > at clojure.lang.Compiler.resolve(Compiler.java:3972) > at clojure.lang.Compiler.analyzeSymbol(Compiler.java:3955) > at clojure.lang.Compiler.analyze(Compiler.java:3686) > ... 3 more > > So it seems that this isn't being treated as a string at all! It > thinks that the slashes are denoting a namespace. What am I missing > here? --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: memory issue with nth
On Dec 7, 11:18 am, Paul Mooser <[EMAIL PROTECTED]> wrote: > I also have this problem, unless I set my heap to be substantial - > going up in increments of 128M, I need to have at least a 768M heap > for this to not occur. That seems completely crazy, but the rest of > you are saying you don't have this issue. I am not seeing this problem. I set the heapsize down to 32M but this still works. [parth:~]% java -Xmx32M -cp /home/parth/src/clojure/clojure.jar clojure.main Clojure user=> (nth (repeatedly (fn [] 0)) 1000) 0 user=> (.maxMemory (Runtime/getRuntime)) 33357824 user=> (nth (repeatedly (fn [] 0)) 1) 0 user=> (System/getProperty "java.version") "1.6.0_07" user=> This is on debian. Parth > > Maybe it's time to start looking at what platforms we are running, and > how much memory you have the JVM configured to use? If people have > their heap set to be large enough, they might not realize this is > happening, or if it is a bug on a subset of platforms, then that might > explain it as well. > > I'm running on OS X Leopard, and I've tried both the 1.5 and 1.6 JVMs. > I don't normally pass any non-standard memory size arguments to the VM > unless I expect I'll need it for something I'm doing. --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Running clojure-contrib.jar
On Dec 7, 3:51 am, janus <[EMAIL PROTECTED]> wrote: > All, > > It is my mistake, this is the error once again. Failed to load Main- > Class manifest attribute from C:\clojure\clojure\clojure-contrib.jar. > I did what Shulz said , however , I still have the same problem. > Could you copy the error messages to the list? That would help in understanding the error better. Also, are you using the latest sources from the svn or the released version? In there latest sources there are some enhancements to the main (like adding -h, -e options etc.). So, with the latest svn HEAD, the windows equivalent of the following should work for you: java -server -cp /home/parth/src/clojure/clojure.jar:/home/parth/src/ clojure-contrib/clojure-contrib.jar clojure.main Note that on windows, apart from the path changes you would need to use ";" instead of ":". Parth > Emeka > > On Dec 6, 7:17 pm, Stuart Halloway <[EMAIL PROTECTED]> wrote: > > > If you have a space between "jar" and ";" that is a problem. > > > Stuart > > > >> Start by telling us precisely what you did to "run clojure." > > > > I have the below in my batch file > > > SET CLASSPATH=/clojure/clojure/clojure.jar > > > /clojure/clojure/clojure-contrib.jar;\ > > > java clojure.lang.Repl > > > > To run means clicking batch file. I followed the instructiom from > > > Clojure Programming Book. > > > I got a message box with the "Failed to load Main-Class manifest > > > attribute from C;/clojure/ > > > clojure/clojure". On click ok, it opened the Repl. > > > > Emeka > > >> Also: Sometimes for things like this asking on the #clojure IRC > > >> channel > > >> is more expedient, assuming it's a time of day when many people are > > >> around. > > > >>> Emeka > > > >> Randall Schulz- Hide quoted text - > > > - Show quoted text - --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Atoms
Thanks for taking to time for such a detailed explanation Rich. This makes things much clear. And thanks Chouser for the pictorial representation. Parth On Dec 5, 6:24 pm, Rich Hickey <[EMAIL PROTECTED]> wrote: > On Dec 5, 5:51 am, bOR_ <[EMAIL PROTECTED]> wrote: > > > Are there any screencasts planned which will feature atoms? (I found > > that the screencasts are an excellent way of learning clojure). > > Screencasts are generally a side-effect of a speaking engagement. I > imagine next time I give a talk, I'll talk about atoms too. > > To address the general question about when to use atoms/refs/agents, > it helps to think of things this way: > > First, note that in talking about atoms/refs/agents we are talking > about Clojure's reference types that allow changes to be seen by > multiple threads, so these three reference types are all shared > reference types. > > There are two dimensions to the choice about using them, the first is > - will the changes be synchronous or asynchronous, and the second is, > will a change to this reference ever need to be coordinated with a > change to another reference or references. > > Chouser made a nice diagram after I described this on IRC: > > http://clojure.googlegroups.com/web/clojure-conc.png > > As you can see, for coordinated changes, refs + transactions are the > only game in town, and asynchrony (beyond a set of commutes) doesn't > make much sense, so no reference type is coming to replace the X. > > For independent change, you have two choices, agents and atoms. > > Atoms are synchronous, the change happens on the calling thread. They > are as close to a plain variable as you get from Clojure, with a > critical benefit - they are thread safe, in particular, they are not > subject to read-modify-write race conditions. Your writes don't happen > unless they are a function of what was read. But modifications to > atoms are side effects, and thus need to be avoided in transactions. > > Agents are asynchronous, and that can have important benefits. In > particular, it means actions get queued, and the sender can proceed > immediately. They provide a transparent interface to the threading > system and thread pools. Agents also cooperate with transactions in > ways that atoms cannot - e.g. agent sends are allowed in transactions > and get held until commit. > > What's nice is the unified model underlying the reference types. All > can be read via deref/@, all are designed to refer to an immutable > data value, and to model change as a function of that value. All > support validators. > > What that means is that, if you build your state transformation > functions as pure functions, you can freely choose/switch between the > different reference types, even using the same logic for two different > reference types. > > However, they are different, and they have not been unified in the > areas in which they differ, in particular, they each have a unique > modification vocabulary - ref-set/alter/commute/send/send-off/swap!/ > compare-and-set!. > > In the end, Clojure is a tool, and will never be able to make > architectural decisions for you. Hopefully the above will help you > make informed choices. > > The memoization example is a prime motivating case for atoms - a local > cache. It's also one that people routinely get multithread-wrong when > trying to implement with simple mutable variables. > > Rich --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Atoms
On Dec 5, 6:02 am, Rich Hickey <[EMAIL PROTECTED]> wrote: > I've added a new reference type - atom. > > Docs here: > > http://clojure.org/atoms > > Feedback welcome, > > Rich Are the following equivalent or is one recommended over the other? The first (using atoms) is definitely more convenient and less verbose. user=> (def a (ref {:a 1 :b 2 :c 3})) #'user/a user=> (def a (atom {:a 1 :b 2 :c 3})) #'user/a user=> (swap! a assoc :a 5) {:c 3, :b 2, :a 5} user=> a # OR user=> (def b (ref {:a 1 :b 2 :c 3})) #'user/b user=> (dosync (ref-set b (assoc @b :a 5))) {:c 3, :b 2, :a 5} user=> b # user=> @b {:c 3, :b 2, :a 5} user=> Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Serializing Clojure objects
On Dec 2, 11:52 pm, Rich Hickey <[EMAIL PROTECTED]> wrote: > As part of AOT I needed to enhance print/read to store constants of > many kinds, and restore faithfully. This led to a new multimethod - > print-dup, for high-fidelity printing. You can get print-dup behavior > by binding *print-dup*: > ... > > It can handle all of the Clojure data structures (including sorted > variants), Java collections, classes etc. > > You can extend it to new types by defining the print-dup method for > the type. > > Rich Very cool. I did not know much about print-dup and the support for java collections. Thanks. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Serializing Clojure objects
Tayssir John Gabbour wrote: > Hi! > > How should I approach serialization? I made a little test function > which serializes and deserializes Clojure objects. It works for > strings, integers, symbols, LazilyPersistentVectors and.. oddly.. > PersistentHashMaps that have exactly one element. (My Clojure is about > a month old.) > I am not much of a Java guy so this would be what I would do. Clojure has reader syntax of its data structures (maps, vectors etc.) so they can be easily written to a stream as test using write. Reading it is equally simple: user=> (def a (with-in-str "{:a 1 :b 2}" (read))) #'user/a user=> a {:a 1, :b 2} user=> So as long as your data has reader syntax its not too much of an issue. If the data needs to be shared between languages as highlighted by someone, you may consider using another format like json or so. If the data used java object it may not be serializable so easily. Generally my approach is to stick to data structures at Clojure level as it has reader syntax. Parth > But for other things, like keywords and most PersistentHashMaps, it > throws NotSerializableException. > > My imagined possible solutions: > > * Implement Serializable for Clojure data -- but is it possible in a > dynamic "Hey I'll just write a new method!" way? > > * Go into Clojure's source and implement Serializable to the Java > classes. > > > My end goal is using a nonrelational DB like Tokyo Cabinet or > BerkeleyDB. > > Thanks, > Tayssir > > > PS: Here's my test code: > > (defn my-identity "Copies obj through serialization and > deserialization." > [obj] > (let [byte-out (new java.io.ByteArrayOutputStream) > obj-out (new java.io.ObjectOutputStream byte-out)] > (try (.writeObject obj-out obj) > (finally (.close obj-out))) > (let [obj-in (new java.io.ObjectInputStream >(new java.io.ByteArrayInputStream (.toByteArray > byte-out)))] > (try (.readObject obj-in) >(finally (.close obj-in)) --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: SVN or release?
Kyle Schaffrick wrote: > Hi all, > > I've been playing with Clojure for a few days now, following the mailing > list, searching and tinkering, etc. I'm really excited about this > language! > > I'm running the latest packaged release, and I'd like to start writing > some more serious "spikes" in Clojure, but I'm starting to get the > impression that I should be using the SVN version instead to get the > latest hotness. > > I say this because I've noticed a few things here and there in 3rd party > code and in the docs that are not working, it seems, because they depend > on features/changes only present in SVN, such as the Java method call > operators, and some namespace shuffling. Being a Vimmer, for example, I > tried to set up Chimp and am getting a mysterious exception from the > STM's innards when Vim tries to connect to Chimp's REPL listener. > > Is there a general recommendation here? Should I be on SVN or is this > just my bad luck :) I think Rich is working towards a 1.0. For now I prefer to follow svn HEAD. Its best to check the svn release log before using just in case there are any intermediate checkins. These are typically marked "Interim checkin - DO NOT USE!!" in the log. I plan to stick to releases post 1.0. Regarding Chimp, maybe you can try Gorilla: http://groups.google.com/group/clojure/browse_thread/thread/c8b7bc3106c39791 I haven't used it personally yet. Parth > > Thanks, > -Kyle --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: NullPointer when just returning nil?
On Nov 29, 6:03 pm, "Ralf Bensmann" <[EMAIL PROTECTED]> wrote: > But #(...) and (fn [] ...) should be the same? I suppose that might make the syntax somewhat ugly. E.g.: (fn [x] (foo x)) would become #((foo %)). This particular syntax is a frequent point of confusion but then once you get it its cleaner. The current syntax fits the common case better where you might do #(foo %1 %2) sort of a thing. I suppose once an FAQ for Clojure comes up this goes there :) Parth > > On Sat, Nov 29, 2008 at 1:48 PM, Parth Malwankar > <[EMAIL PROTECTED]>wrote: > > > > > On Nov 29, 5:29 pm, "Ralf Bensmann" <[EMAIL PROTECTED]> > > wrote: > > > Hi, > > > > is this the intended behavior? > > > > user=> #(nil) > > > java.lang.NullPointerException (NO_SOURCE_FILE:12) > > > user=> (def b #(nil)) > > > java.lang.NullPointerException (NO_SOURCE_FILE:13) > > > This is expected. > > #(nil) is the same as (fn [] (nil)) and hence the failure. > > (fn [] nil) is what you want. > > > > This works: > > > user=> #('nil) > > > # > > > I am not very clear on whats happening here to comment. > > > Parth > > > > Thanks, > > > -Ralf --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: NullPointer when just returning nil?
On Nov 29, 5:29 pm, "Ralf Bensmann" <[EMAIL PROTECTED]> wrote: > Hi, > > is this the intended behavior? > > user=> #(nil) > java.lang.NullPointerException (NO_SOURCE_FILE:12) > user=> (def b #(nil)) > java.lang.NullPointerException (NO_SOURCE_FILE:13) > This is expected. #(nil) is the same as (fn [] (nil)) and hence the failure. (fn [] nil) is what you want. > This works: > user=> #('nil) > # > I am not very clear on whats happening here to comment. Parth > Thanks, > -Ralf --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: File Copy
On Nov 24, 12:34 am, Stuart Sierra <[EMAIL PROTECTED]> wrote: > Honestly, for this kind of low-level stuff I always use the Apache > Commons libraries, <http://commons.apache.org/>, esp. the Lang and IO > components. They've got every imaginable stream function, all > carefully and efficiently implemented. But if you're determined to do > it in Clojure, loop/recur is the way, as James demonstrated. > -Stuart Sierra Yes. commons.io.FileUtils.copyFile is definitely a nicer way :) I am still learning Java (as an when I need it for Clojure). Thanks for the pointer. Thanks James for the pipe-stream. Here is the copy: (defn copy [iname oname] (let [in (new FileInputStream iname) out (new FileOutputStream oname) buffer (make-array Byte/TYPE 1024)] (loop [len (.read in buffer)] (when (pos? len) (.write out buffer 0 len) (recur (.read in buffer)) Parth > > On Nov 23, 1:35 pm, Parth Malwankar <[EMAIL PROTECTED]> wrote: > > > Hello, > > > I am trying to translate the following Java > > snippet into a file copy routine in Clojure. > > > public static void copy(InputStream in, OutputStream out) throws > > IOException { > > byte[] buffer = new byte[1024]; > > while (true) { > > int bytesRead = in.read(buffer); > > if (bytesRead == -1) break; > > out.write(buffer, 0, bytesRead); > > } > > } > > > I was barely able to start: > > > (defn copy [iname oname] > > (let [in (new FileInputStream iname) > > out (new FileOutputStream oname)] > > nil)) > > > But now I am totally lost at the "nil". I am not sure how to translate > > the "while" loop. > > > I would appreciate any pointers on how to do this (or maybe a more > > ideomatic > > way). > > > Thanks. > > Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
File Copy
Hello, I am trying to translate the following Java snippet into a file copy routine in Clojure. public static void copy(InputStream in, OutputStream out)throws IOException { byte[] buffer = new byte[1024]; while (true) { int bytesRead = in.read(buffer); if (bytesRead == -1) break; out.write(buffer, 0, bytesRead); } } I was barely able to start: (defn copy [iname oname] (let [in (new FileInputStream iname) out (new FileOutputStream oname)] nil)) But now I am totally lost at the "nil". I am not sure how to translate the "while" loop. I would appreciate any pointers on how to do this (or maybe a more ideomatic way). Thanks. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: printing *command-line-args*
On Nov 20, 10:49 pm, "Tom Emerson" <[EMAIL PROTECTED]> wrote: > On Thu, Nov 20, 2008 at 12:37 PM, Parth Malwankar > > <[EMAIL PROTECTED]> wrote: > > I have a single line file (tmp.clj) where I am trying to > > print *command-line-args*. > > And I get an exception if I run it. I am not sure what I > > am doing wrong here. > > I suspect the issue is in your 'clj' script: the command-line > arguments follow two dashes ("--"): anything before that (and after > your initial script name) constitute files that Clojure will attempt > to load in addition to the first: this allows you to load multiple > .clj files on the command-line. My variant of 'clj' looks like (with > classpath noise removed): > > java clojure.lang.Script "$1" -- "$@" Yes. That did the trick. Thanks very much. I had blindly copied the clj script from the wiki. Parth > > $ clojure tmp.clj foo bar baz > ("tmp.clj" "foo" "bar" "baz") > > Hope this helps. > > -- > Tom Emerson > [EMAIL PROTECTED]://www.dreamersrealm.net/~tree --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
printing *command-line-args*
Hello, I have a single line file (tmp.clj) where I am trying to print *command-line-args*. And I get an exception if I run it. I am not sure what I am doing wrong here. [parth:~]% cat tmp.clj (prn *command-line-args*) [parth:~]% clj tmp.clj hello world nil Exception in thread "main" java.io.FileNotFoundException: hello (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:106) at java.io.FileInputStream.(FileInputStream.java:66) at clojure.lang.Compiler.loadFile(Compiler.java:4395) at clojure.lang.Script.main(Script.java:65) [parth:~]% clj tmp.clj nil I am using clojure from HEAD. Any suggestions appreciated. Thanks. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: A value that equals everything, or, ignoring things in multi-dispatch
On Nov 16, 12:36 am, samppi <[EMAIL PROTECTED]> wrote: > Is there a way to get a value—call it 'anything—so that (isa? anything > x) is always true for any x? > > I need this for multimethod dispatch—sometimes, I want a method to > ignore some of the stuff its dispatch function returns: > > (defmulti a #(%1 %2)) > > (defmethod a [3 2] [x y] ...) > > ; in this method, the second dispatch value is ignored and > ; the method matches any call whose first argument is 5 > > (defmethod a [5 anything] [x y] ...) > > I wish the _ symbol would do this, but it doesn't work (if practical, > it'd be cool if it were implemented in the future :). Is there some > sort of solution possible right now? There could be some problem constraints I don't understand here but maybe you could just use "first" (or some custom function) to extract the relevant args user=> (defmulti a #(first [%1 %2])) #'user/a user=> (defmethod a 3 [x y] :three) # user=> (defmethod a 5 [x y] :five) # user=> (a 3 4) :three user=> (a 3 5) :three user=> (a 5 5) :five Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Changes for AOT compilation
On Nov 13, 11:43 pm, Rich Hickey <[EMAIL PROTECTED]> wrote: > We're coming around the other side of the few breaking changes I > wanted to get done before release 1.0. > > The changes are: > > New regex format: > > http://groups.google.com/group/clojure/msg/eddd7f0d292da683 > > Uniform binding syntax using vectors: > > http://groups.google.com/group/clojure/browse_frm/thread/55213f2eb203... > > And ahead-of-time (AOT) compilation (SVN 1094+) Thanks very much Rich. All these changes are very exciting. I look forward to using them. Does this mean that at some point clojure.jar would contain precompiled class files for clojure code? I suppose that would mean faster startup of the repl. Parth > > There is now an AOT compiler that can compile .clj files to .class > files on disk. This can be used to save startup time, deliver > applications without source, interop with bytecode-based tools etc. > > The main structural change related to AOT is that the mapping between > a Clojure namespace and a Java package has changed. Where it was ns > maps to package: > > my.fancy.lib ==> my/fancy/lib/lib.clj > > it is now ns maps to class: > > my.fancy.lib ==> my/fancy/lib.clj, when compiled, my/fancy/lib.class > > Just lift your files up a directory to accommodate this change. Note > that this implies that all namespaces should have at least 2 segments, > and following the Java package name guidelines, e.g. > com.mydomain.mylib, is recommended. > > Accordingly, the clojure ns has been renamed clojure.core. Any > explicitly qualified references will need to be changed. boot.clj has > been renamed core.clj. > > The only other source-level change here was a small one to load - you > no longer should supply the .clj extension, in keeping with load's new > ability to load from .class files. > > The latter is the only functional difference AOT brings to existing > code - load will load from a .class file if it is newer than the .clj. > Both files need to be in the classpath, using a directory structure > corresponding the the Java package as per above. Once compiled, .clj > files need not be present at all if .class files are supplied. > > The unit of compilation is the lib. To compile a lib, simple say: > > (compile 'my.fancy.lib) > > The source must be in the classpath, in my/fancy/lib.clj Compilation > output will go under the path designated by *compile-path*, which > defaults to the "classes" directory under cwd. Output will go to > *compile-path*/my/fancy/lib.class, and the subdirectories will be > created if needed. *compile-path* is bound in the repl and can be set! > or bound with binding. The *compile-path* directory must also be in > the classpath. > > Compilation occurs under a same-world model, i.e. compiling a file has > the effect of loading it as well. As each file/fn is compiled, it is > loaded using the standard class lookup (thus the *compile-path* in > classpath requirement above). This is so that definitions can see and > utilize the definitions and macros that preceded them. While > compiling, a *compile-files* flag is set. This will cause nested load/ > require/uses to compile as well, if needed. If your file has some def > initializers you don't want to run at compile-time, you can > conditionalize them like this: > > (def foo (when-not *compile-files* (my-runtime-init))) > > in which case foo will be nil at compile time. > > A .class file will be produced for every file loaded. This file > defines a class called my.fancy.lib, which will have a static void load > () method (this name is likely to change). Calling this method has the > same effect as loading the original .clj would. > > Namespaces defined in multiple files are supported. Simply (load "lib- > helper-file") for any helper files at the bottom of your ns- > defining .clj file. Note that classes will be created for these files > as well, even though they are not namespaces, and are not intended for > standalone use > > In addition to the class file per .clj file, there will be a .class > file for every function. These will be named my/fancy/lib > $myfun__.class. They too are not intended for standalone use. > There will be many of these, so please use jar files for distribution. > > The clojure.contrib and tools folks are working on getting in sync > with these changes. For minimal disruption, please stick with the SVN > rev they support (say, 1088), or lend a hand in testing their patches. > > Still to come is a folding of genclass functionality into AOT, making > for a much smoother process. > > Those of you who've used Clojure for a while know such breaking > changes are few an
Re: clojure.zip: replace error
On Nov 14, 9:47 am, Rich Hickey <[EMAIL PROTECTED]> wrote: > On Nov 13, 11:20 pm, Parth Malwankar <[EMAIL PROTECTED]> > wrote: > > > Hello, > > > While setting ns to clojure.zip, I get the following error: > > > user=> (ns clojure.zip) > > java.lang.IllegalStateException: replace already refers to: > > #'clojure.zip/replace in namespace: clojure.zip (NO_SOURCE_FILE:0) > > clojure.zip=> > > > Is this expected? > > Do not use ns to change namespaces, use in-ns. ns is for defining a > namespace. Works nicely. Thanks for the clarification. Above may be good to addition to (doc ns) just to be sure :) Parth > > Rich --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
clojure.zip: replace error
Hello, While setting ns to clojure.zip, I get the following error: user=> (ns clojure.zip) java.lang.IllegalStateException: replace already refers to: #'clojure.zip/replace in namespace: clojure.zip (NO_SOURCE_FILE:0) clojure.zip=> Is this expected? Thanks. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: iterate
On Nov 13, 12:25 pm, notallama <[EMAIL PROTECTED]> wrote: > i put this at the end of my boot.clj for added fun: > > (defn iterate > "returns a lazy seq of arg1, arg2 ... argn, (f arg1 ... argn), (f > arg2 ... argn (f arg1 ... argn)), etc." > [f & [x & rest :as all]] > (lazy-cons x (apply iterate f (concat rest [(apply f all)] > > user=> (take 10 (iterate + 1 1)) > (1 1 2 3 5 8 13 21 34 55) > > user=> (take 4 (iterate #(* % %) 2)) > (2 4 16 256) > > is this good as a contrib? is there a better way to implement this? There is already an "iterate" in Clojure. Your implementation much have shadowed it. user=> (doc iterate) - clojure/iterate ([f x]) Returns a lazy seq of x, (f x), (f (f x)) etc. f must be free of side-effects nil user=> (iterate #(+ 1 %) 1) (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 3 0 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 ...) But it doesn't take multiple arguments like your implementation. Thats a nice enhancement. Parth > also, this language is delightful. --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Can't get rlwrap to work
On Nov 13, 2:38 am, Giacecco <[EMAIL PROTECTED]> wrote: > Hi all, > I am trying setting up clojure to use rlwrap as described > athttp://en.wikibooks.org/wiki/Clojure_Programming#Enhancing_Clojure_RE... > on a MacOS 10.5.5. > > I have prepared the clj-completions.clj the instructions describe, but > it fails on the second of the three commands. If I run it from the > console, I see the following: > > gianfranco-cecconis-macbook-pro:clojure giacecco$ clj > Clojure > user=> (defmacro with-out-file [pathname & body] > `(with-open stream# (new java.io.FileWriter ~pathname) > (binding [*out* stream#] > [EMAIL PROTECTED]))) > nil > user=> (def completions (keys (ns-publics (find-ns 'clojure > java.lang.NullPointerException (NO_SOURCE_FILE:5) > user=> This works fine for me on WinXP and Linux. Haven't tried MacOS. Are you using the latest sources from svn? The HEAD (between ~1088 and 1095 IIRC) was in a state of flux for AOT support. So you could try the released version or 1087 or so. > > What does that "NO_SOURCE_FILE:5" mean? Thank you in advance! Error messages from Clojure indicate the line with error using the source:line_no format. For the REPL there is no source file hence NO_SOURCE_FILE:5. Parth > > Giacecco --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Patch: callable defstruct (PersistentStructMap$Def extends AFn)
On Nov 6, 9:19 am, Chouser <[EMAIL PROTECTED]> wrote: > On Wed, Nov 5, 2008 at 12:10 AM, Chouser <[EMAIL PROTECTED]> wrote: > > The attached patch allows: > > > user=> (point 42 11) > > {:x 42, :y 11} > Seems like a very nice enhancement to me. It would make the code more terse. Parth > The right tool for the job makes all the difference. Attached is a > much simpler patch to accomplish the same thing. > > --Chouser > > structmap-def-extends-restfn.patch > 1KViewDownload --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Files in Clojure Google Groups
Rich Hickey wrote: > On Oct 30, 3:57 pm, bc <[EMAIL PROTECTED]> wrote: > > Hi all, > > > > Is there any way to enter an annotation or comments when a file is > > uploaded to the Clojure Google Groups file area? I've recently had a > > look at a few things there and it would be nice to have some context > > or background on why they were uploaded. For example, "tsp.zip" is a > > Traveling Salesperson example but, unless you download it and look at > > the code, how would you know that? Another example is "Clojure.png" > > which has a nice graphical representation of the Clojure reader. Was > > this part of a documentation effort or was it uploaded as an example > > as part of a discussion (a search on "Clojure.png" in the group didn't > > produce any matches)? It would be nice to have some form of comments/ > > annotations about the files. > > > > > That's a good point. Unfortunately, it doesn't look like Google Groups > supports any annotations on the files. Suggestions for alternatives > welcome. Recently I noticed that the vim_dev google group set up the "pages" section to list patches and their summary. http://groups.google.com/group/vim_dev/web/vim-patches Maybe something like that can be used. Parth > > Rich --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: lazy death
On Oct 25, 5:27 pm, Timothy Pratley <[EMAIL PROTECTED]> wrote: > > (set! *print-length* 50) > > Ah perfect. Thanks! Is there a way to make this default? clojure.lang.Repl will run all the files listed before it goes to the prompt. So I have my clj script updated to accept a .cljrc.clj file that has my settings: clj launch script -- start: #!/bin/bash BREAK_CHARS="(){}[],[EMAIL PROTECTED]";:'|\\" CLJRC=~/.cljrc.clj if [ $# -eq 0 ]; then rlwrap --remember -b $BREAK_CHARS -f /home/ parth/.clj_completions \ java -server -cp $CLASSPATH clojure.lang.Repl $CLJRC else java -server -cp $CLASSPATH clojure.lang.Script "$@" fi clj launch script -- end: Note the $CLJRC above. On windows you should be able to do something similar to the batch file you use for launching clojure repl (clj.bat I assume from http://en.wikibooks.org/wiki/Clojure_Programming#Installation) Note the I haven't used $CLJRC for clojure.lang.Script as I want to run my scripts in a clean environment. You could use $CLJRC with scripts also if you want to. .cljrc.clj file -- start: (set! *print-length* 50) (set! *print-level* 10) . cljrc.clj file -- end: I then to use the .cljrc.clj file for any settings I want to use across repls (including any convenience functions as it just a regular clojure source file). Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: lazy death
On Oct 25, 4:55 pm, Timothy Pratley <[EMAIL PROTECTED]> wrote: > When I screw up a lazy-cons (which happens quite a lot to me), > my repl goes nuts and appears to corrupt the box it lives in. If I > leave it running my monitor blanks out periodically... like some > system register got reset. I can't break the cycle with ctrl-c. > Here is a screenshot of the corruption > starting:http://groups.google.com/group/clojure/web/lazy-death.PNG > > I realise that this isn't a clojure problem (its doing what I told it > to), more an environment issue. > Currently Im using winXP cmd box to start the repl. > Below is an example of how to reproduce: > > (defn lazy-death [x & more] > (lazy-cons x (lazy-death more))) > user=> (lazy-death [1 2 3]) > ; fills the box with nil, then colors go wonky, then monitor may reset > periodically > > ; I made a silly omission, can fix it easily: > (defn lazy-death [x & more] > (when x (lazy-cons x (lazy-death more > user=> (lazy-death [1 2 3]) > ([1 2 3]) > > I guess maybe its just the windows cmd box floods the monitor somehow > with the nils? Anyhow... is there any way to save me from myself in > this scenario? I find when I'm working on a lazy-cons I spend most of svn rev 1077 has a patch for *print-length* and *print-level*. Discussed here: http://groups.google.com/group/clojure/browse_thread/thread/3664c80d9d45f2c7# This handles the issue. With: (set! *print-length* 50) (set! *print-level* 10) I get: user=> (lazy-death [1 2 3]) ([1 2 3] nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil ...) user=> You would need to get the latest sources from svn for this to work. Parth > my time opening cmd boxes to replace the ones I've killed off :) > > What does work is invoking as a script... ie: > edit foo.clj > clj foo.clj > ; here I can press ctrl-c and break from the loop, fix it and try > again > > My prefered work flow is copy+pasting to a repl snipets from my main > source. > > Regards, > Tim. --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Clojure and introspection/reflection analysis?
On Oct 24, 3:42 am, BerlinBrown <[EMAIL PROTECTED]> wrote: > I asked this on common lisp thread but I want to work with clojure as > well: > > With clojure and I am assuming the introspection properties. How > can I add code to clojure code that will tell me when a function > is called and when has finished executing. I want to take any lisp > code and this particular modification to the code. I figure with > lisp's AST analysis, this should be possible. > > For example, pseudo code in common lisp, hello_world.lisp: > > (defun hello-world () > (format t "Hello World")) > > (hello-world) > > And then I have a utility to load hello_world.lisp and execute > the hello-world call. > > At the command line: > #Inspect: hello-world function was called > #Hello World > #Inspect: hello-world has finished executing. This message also points to one way of doing this: http://groups.google.com/group/clojure/msg/91b028c63ec440d6 Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Reader + Macros on untrusted S Expressions: Security considerations?
On Oct 22, 3:42 pm, Parth Malwankar <[EMAIL PROTECTED]> wrote: > On Oct 22, 1:30 pm, "Brett Morgan" <[EMAIL PROTECTED]> wrote: > > - Recently the #= reader macro was added. This makes the reader > do the evaluation before using the value. You may want to > disable this. E.g. > > user=> #=(+ 1 1) > 2 > > I am not sure how to disable this. There is a > similar thing #. in CL and it is important to disable it before > reading potentially unsafe expressions. Maybe Rich or someone > else can comment on how to disable this. > Oops. The example I meant to give was: user=> `(+ 1 1) (clojure/+ 1 1) user=> `#=(+ 1 1) 2 Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Reader + Macros on untrusted S Expressions: Security considerations?
On Oct 22, 1:30 pm, "Brett Morgan" <[EMAIL PROTECTED]> wrote: > Hi all, > > I am thinking about a potential architecture for a webapp where in the > server gets s expressions posted from an ajax web client. > > From a security standpoint, the s expressions are coming from an untrusted > computer, and thus are in need of careful vetting. > > With my java dev hat on, i'd move forward by building a lexer, a parser, and > a tree walker to interpret the incoming datastream, with careful > consideration to the various potential attacks a malicious user can submit. > > I understand the lisp way is to use the reader plus macros to interpret the > incoming data stream. This is hella cool in that it seriously cuts down on > the amount of development work I have to do. The reader is already done, and > using macros to build the tree walker? And have them applied to a stm core? > Very lightweight in comparison to what I'd do traditionally. Very cool. > > My concern is, what are the security considerations of this architectural > choice? Do I have to worry about people submitting malformed s expressions? > Submitting s expressions that contain data that expands out reader macros? > Do I have to watch for any particular bad code practices in constructing the > macros? How do I go about error recovery and reporting on bad input? > > Thanks in advance. > Hi Brett, Yes, being able to use the clojure reader directly is really neat. Some things you could do are: - use a separate namespace for evaluation the expressions and provide a clear interface between the core and the sexpressions that you get. - have a black or white list, and allow or reject the s-expression based on this. For example you might want to disallow namespace switching functions. E.g. below, I can't clobber defn as I am in the 'user' namespace and 'defn' is in the clojure ns. user=> (def defn :somethig-bad) java.lang.Exception: Name conflict, can't def defn because namespace: user refers to:#=(var clojure/defn) (NO_SOURCE_FILE:1) user=> Some other things you may want to reject expressions based on are java interop and file IO. This should basically be a find operation for a bunch of symbols on the list before you give it to the reader 'read' - Recently the #= reader macro was added. This makes the reader do the evaluation before using the value. You may want to disable this. E.g. user=> #=(+ 1 1) 2 I am not sure how to disable this. There is a similar thing #. in CL and it is important to disable it before reading potentially unsafe expressions. Maybe Rich or someone else can comment on how to disable this. I suppose a lot of this is dictated by what you want to do with the s-expressions. Parth > -- > > Brett Morganhttp://brett.morgan.googlepages.com/ --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: importing clojure.contrib.miglayout
On Oct 21, 8:30 pm, "J. McConnell" <[EMAIL PROTECTED]> wrote: > On Tue, Oct 21, 2008 at 11:19 AM, Parth Malwankar > > <[EMAIL PROTECTED]> wrote: > > > I am trying to import clojure.contrib.miglayout. The simple "import" > > seems to work fine, but the moment I use ":require" it fails. > > Am I doing something wrong here or is this a bug? > > Seems to work for other modules like pred and command_line. > > > [parth:~]% clj > > Clojure > > user=> (ns test (:refer-clojure) (:require clojure.contrib.miglayout)) > > java.lang.ClassNotFoundException: net.miginfocom.swing.MigLayout > > (miglayout.clj:0) > > I don't have any experience with that library, but it looks like you > are missing a jar in the classpath. There's probably a third-party jar > that provides the net.miginfocom.swing.MigLayout class. > > - J. Yes. Thats was it. Wow I feel stupid :) Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
importing clojure.contrib.miglayout
Hello, I am trying to import clojure.contrib.miglayout. The simple "import" seems to work fine, but the moment I use ":require" it fails. Am I doing something wrong here or is this a bug? Seems to work for other modules like pred and command_line. [parth:~]% clj Clojure user=> (ns test (:refer-clojure) (:require clojure.contrib.miglayout)) java.lang.ClassNotFoundException: net.miginfocom.swing.MigLayout (miglayout.clj:0) test=> (ns test (:refer-clojure) (:require clojure.contrib.pred)) nil test=> (import '(clojure.contrib.miglayout)) nil test=> (ns test (:refer-clojure) (:require [clojure.contrib.miglayout :as miglayout])) java.lang.ClassNotFoundException: net.miginfocom.swing.MigLayout (miglayout.clj:0) test=> Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Multiple return values
On Oct 20, 3:51 pm, "Fredrik Appelberg" <[EMAIL PROTECTED]> wrote: > Hi all, > > The CL feature for handling multiple return values from a function come in > really handy sometimes and make for cleaner APIs. For example, the ROUND > function returns the integer part of a float as the regular value (as this > is what you want most of the time), but optionally also returns the floating > point part in case you want it. > > I haven't found anything like MULTIPLE-VALUE-BIND in Clojure. Are there any > plans of incorporating any kind of mechanism for multiple return values? Hi Fredrik, Similar results can be accomplished using vectors and destructuring in Clojure. user=> (defn foo [] [:one :two :three]) #=(var user/foo) user=> (let [[a b c] (foo)] (println b)) :two nil user=> The destructuring capabilities of "let" are quite nice. A bunch of examples are available in the let reference: http://clojure.org/special_forms Parth > > Cheers, > -- Fredrik > == > What am I up to?http://twitter.com/appelberg --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Newbie question on the use of functional hash maps
On Oct 20, 6:16 am, "Tom Emerson" <[EMAIL PROTECTED]> wrote: > Hi all, > > I have a somewhat embarassing newbie question on the use of hash maps > in a functional environment. > > Consider a little utility that counts the number of unique words in a > file. A hash map mapping strings to integers is the obvious data > structure for this, but the fact that (assoc) returns a new map each > time it is called is tripping me up: since I can't define a 'global' > hash map to accumulate the counts, do you pass one around in a > function? or do you structure the code a different way? This is a > difference from what I would do in Common Lisp, where I would just > have a global that is used for the collection. The word count program already mentioned in this thread is nice. If you do need to maintain state, this thread has some pointers: http://groups.google.com/group/clojure/browse_thread/thread/a60b20955ad47fca Parth > > Thanks in advance for your wisdom. > > -tree > > -- > Tom Emerson > [EMAIL PROTECTED]://www.dreamersrealm.net/~tree --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Suggestions on handling state for a game...
On Oct 20, 1:38 am, Adam Jones <[EMAIL PROTECTED]> wrote: > I'm starting up work again on my Clojure-based game. Up until this > point I've been doing things the "dirty" way by re-defing a bunch of > global variables and/or storing the values in the Java objects I need > to use to get access to the game framework. > > This approach is pretty unwieldy, and means I miss out on a lot of the > cool things Clojure has to offer. So, I need to figure out how to > handle state from within Clojure. The two ideas that I think will work > are: > > 1. Store the game world as a var, and have the game structured as a > function from the game world to the game world. Since I need to pass > control back to Java to handle a lot of the details this would require > me to store the game world in Java between updates. > > 2. Store the game world as a ref and use the facilities of that to > modify the game state on updates. This seems cleaner in that it can > all be handled without resorting to Java for intermediary storage. I > am concerned that using the STM system would add too much performance > overhead. > Hi Adam, In such a scenario, I would probably go with option (2) that you outlined. A good example is available here: http://en.wikibooks.org/wiki/Clojure_Programming#Mutation_Facilities The approach would be to define your game as a clojure namespace with pure functions that take the entire game state and return the update state. This will make the functions and the game easier to test and debug. (corresponding to the private functions update-role and delete-by-name in the employee example above). There can be a thin wrapper (your main application) that manages state using refs and the library functions defined above (corresponding to update-employee-role and delete-employee-by-name in the employee example). The main game loop can probably be built around the wrapper functions that work with refs to handle state. > I guess what this all comes down to is, between vars and refs, which > one is the better choice for a program that I don't think will really > need multithreading? Even if the program does not need multi-threading it would be nicer (and easier) to go with refs and pure functions. The reason being that it would be easier to test and debug you code. Also, should a need come to make it multi-threaded at a later date, that would be a trivial change in your code. Note that the employee example doesn't use threads. I think the re-defing approach is ok for simple experiments on the REPL but would make programs more difficult to maintain as they grow in size. Performance should really be a problem with refs. A good essay by Rich on Clojures approach to state is http://clojure.org/state Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Fibonacci function performance compare between clojure and scala
On Oct 19, 7:49 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > Clojure's > > (defn fib [n] >(if (or (zero? n) (= n 1)) >1 > (+ (fib (dec n) ) (fib (- n 2) > > (time (fib 36)) > > "Elapsed Time: 10475.325226 msecs" > 24157817 > > Scala's > > def fib(n:Int):Int=if (n==0||n==1)1 else fib(n-1)+fib(n-2) > def time(cal: =>Int)={ > val beginTime=System.currentTimeMillis > cal > val endTime=System.currentTimeMillis > println(endTime-beginTime)} > > fib(36) > res70:Int=24157817 > time(fib(36)) > 263 > I am not a scala expert but I suspect scala Int maps directly to java ints. In clojure, the number are boxed and checked by default IIRC. This would roughly correspond to BigInt in scala. For clojure, you could coerce ints to native java types using (int ..). Also, unchecked-dec could be used. Doing this should make the code as fast as java or scala. There was some discussion along these lines here: http://groups.google.com/group/clojure/browse_thread/thread/4274ce8bd44664ef# That said, for most practical uses the default behavior should be fast enough. Its not considered idiomatic to use coersion and unchecked operation unless absolutely necessary. Parth > Both not tail recursive,both running on Repl (scala's interpreter),but > the difference between two is huge > 10475~263 > My box : Intel core2 cpu 1.86G,2G mem > Clojure and scala both latest build from svn > > any ideas? --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Multiple indexing for vectors/maps
On Oct 19, 3:12 am, kwatford <[EMAIL PROTECTED]> wrote: > Sorry if this has been asked before, but I couldn't find anything on > it. > If I have: (def A [ [ 1 2 3 ] [ 4 5 6 ] ] ) > then if I want to access a specific element, I have to do: > ((A 1) 1) -or- (get (get A 1) 1) get-in is probably what you are looking for. user=> (get-in A [1 1]) 5 There is also, update-in and assoc-in. Parth > I could make a macro for this of course, but I'd kind of like to > change the call semantics for vectors/maps to allow (A 1 1), perhaps > something like: > (myvec index &more) -> (if more (apply (myvec index) more), (get myvec > index)) > > I don't think adding this should conflict with any existing code, > though I did notice that "get" currently accepts and apparently > ignores one extra parameter. > > This seem like a reasonable feature request? --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Callstack from load-file
On Oct 18, 9:40 pm, jim <[EMAIL PROTECTED]> wrote: > Hey all, > > I had a situation where a source file wouldn't load and the error > message was unhelpful: > > java.lang.IllegalArgumentException: Too many arguments to struct > constructor (source-file.clj:0) > > So, I threw together a quick hack to print the call stack: > > (defn callstack-str [thrown] > (let [stk (new java.io.StringWriter) > pw (new java.io.PrintWriter stk)] > (. thrown (printStackTrace pw)) > (str (. stk (toString) > > (defn lf [filename] > (try > (load-file filename) > (catch java.lang.Throwable e > (print (callstack-str e) > > As usual, I'm sure there's a better way, so I'd appreciate hearing > about it. > > Jim Hi Jim, The default behavior of the REPL is to show only the exception to avoid too much clutter on the screen. The special variable *e stores the last exception which can be used to see the stack trace. So one way to do this would be: user=> (defn foo [] (/ 1 0)) #=(var user/foo) user=> (foo) java.lang.ArithmeticException: Divide by zero (NO_SOURCE_FILE:0) user=> *e #=(clojure.lang.Compiler$CompilerException. "java.lang.ArithmeticException: Divide by zero (NO_SOURCE_FILE:0)") user=> (.printStackTrace *e) java.lang.ArithmeticException: Divide by zero (NO_SOURCE_FILE:0) at clojure.lang.Compiler.eval(Compiler.java:4117) at clojure.lang.Repl.main(Repl.java:87) Caused by: java.lang.ArithmeticException: Divide by zero at clojure.lang.Numbers.divide(Numbers.java:142) at user.foo__2478.invoke(Unknown Source) at user.eval__2481.invoke(Unknown Source) at clojure.lang.Compiler.eval(Compiler.java:4106) ... 1 more nil user=> Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: offtopic - where are you come from? (poll)
On Oct 17, 2:27 pm, "Rastislav Kassak" <[EMAIL PROTECTED]> wrote: > Hello Clojurians, > > I think after 1st year of Clojure life it's good to check how far has > Clojure spread all over the world. > > So wherever are you come from, be proud and say it. > > I'm from Slovakia. :) > > RK Bangalore, India. --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Clojure's first year
On Oct 16, 9:36 pm, Rich Hickey <[EMAIL PROTECTED]> wrote: > A year ago today I 'released' Clojure, by sending a message to my jFli > and Foil mailing lists. It got blogged, picked up by Planet Lisp and > redditted in the course of a day or so, and has been a wild ride ever > since. I couldn't have possibly imagined the year Clojure (and I) have > had. > > Community > > Releasing a language means hoping others will use it, and I truly > appreciate the risks taken by those very first users, trying Clojure > of their own interest and initiative with no recommendations or > testimonials. I've tried to repay that interest with support and > explanations, bug fixes and enhancements. Most satisfying has been > seeing a community grow, and gain a collective experience it can > share. We're now at 650 members on the Google Group, and have had over > 4500 message over the year, 500 messages in the first half of October > alone! Even better, only 15% of those messages were mine (down from > 50% in the early days). There are newcomers kicking the tires, people > who've spent enough time to know their way around, and those who, > through their extended experience, really 'get' the model behind > Clojure, and have developed idiomatic sensibilities. In addition, it's > a diverse community, including some Java experts, and some Lisp > experts, with experience in a wide variety of domains, all of which is > being shared too. > > The discourse and attitude has been consistently positive and > supportive, and Clojure has benefitted tremendously from the feedback > and suggestions of the user community. > > Contributors > > Releasing something as open source means hoping that, eventually, > giving something away will yield returns of contributions that will > allow your project to grow in ways you couldn't achieve alone. I'm > happy to see that starting now, as people get familiar enough with how > Clojure works to make tangible contributions. > > A substantial source of contributions that don't end up in Clojure > itself are on the tools side. People have built editor support for > emacs and vim, the enclojure IDE for Netbeans, swank/slime etc. Other > contributions take the form of additions to the wiki, tutorial blogs, > and answering questions on the group and IRC. > > Awareness > > Clojure has gotten a lot of attention - I've been invited to give > talks at the Dynamic Languages Symposium at ECOOP, the European Lisp > Workshop, IBM Research, the JVM Languages Summit, Boston Lisp, and > next week at Lisp 50 at OOPSLA. There has been a lot of blogging, > which continues to grow. Clojure has made its presence felt in both > the Lisp and JVM communities it bridges, which have very little > overlap otherwise. The feedback has been overwhelmingly positive. > > The Language > > I've done almost 600 checkins in the past year. Many were small bug > fixes and enhancements, others were significant features like first- > class namespaces, in-source docs, gen-class and proxy, primitives > support, ad hoc hierarchies, destructuring, list comprehensions, var > metadata, regex support, zippers, first-class sets, agents, struct > maps, java.util integration, parallel support, etc. All of this > happened in a context of considerable stability and robustness, which > is a testament to the Lisp model of using a small core, with most of > the language provided by independent functions and macros. > > Moving Forward > > The net result is that the prospects for Clojure going forward are > very good. The core model of Clojure has held up well and continues to > appeal - accessible, robust, thread-safe, efficient dynamic functional > programming, on a world-class infrastructure, with a huge set of > libraries. Oh yeah, and it's great fun! > > People coming to Clojure now find a vibrant community, plenty of > support, a variety of tools and more on the way, a wiki and blogs full > of examples, a book on the way, many online screencasts and talks, a > huge message archive etc. The language itself continues to grow in > capabilities while remaining stable, and the growing pool of > contributors promises more hands in pursuing bug fixes and new > features. There's still more to do, but more people to do it as well. > > I designed and built Clojure so that I could pursue the next 20 years > of my career in a language I wouldn't mind thinking in. In order to be > commercially accepted, a language needs to be technically viable and > have wide enough awareness and use. I think Clojure has great > prospects in both of those areas, as it continues to improve and usage > grows. > > Thanks to all fo
Re: Ruby => Clojure for Enumerable and Array
On Oct 17, 3:14 am, Mark McGranaghan <[EMAIL PROTECTED]> wrote: > When I first started working with Clojure a while back I tried to get > my bearings by figuring out how to do some basic things in Clojure > that I had previously done in Ruby. With all the recent talk about > the seq api, I thought I'd clean up my notes on Ruby => Clojure for > the Enumerable and Array Ruby classes. > > You can find what I have so far here:http://gist.github.com/17283 > > I hope someone finds this helpful. Comments are appreciated. Thanks Mark. I don't know much of Ruby so can't really comment on the content, but maybe you can add a link for this to the Clojure Programming wikibook (http://tinyurl.com/5jsvcm). This way more Ruby programmers will be able to find and benefit from it easily at a later date. Parth > > - Mark --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: toUpperCase on java.lang.String
On Oct 16, 4:29 pm, Rich Hickey <[EMAIL PROTECTED]> wrote: > On Oct 15, 11:47 pm, "Stephen C. Gilardi" <[EMAIL PROTECTED]> wrote: > > > > > Hi Parth, > > > > But if I do this in a doto, it doesn't seem to work but > > > I don't get any error message. > > > > user=> (doto (new java.lang.String "hello") (toUpperCase)) > > > "hello" > > > user=> (class (new java.lang.String)) > > > #=java.lang.String > > > > Shouldn't this be working? If this is (by design) because strings are > > > immutable (so no doto) shouldn't there be an error message? > > > > What am I missing here. > > > "doto" operates on an object and returns the object that it operated > > on. In your case, it's the original string that gets returned. Strings > > are immutable so the toUpperCase call created a new string which was > > then thrown away. > > > The "->" operator will accomplish what you're looking for here. It > > returns the result of the operations, each result becoming the input > > for the next:: > > > user=> (-> (String. "hello") .toUpperCase) > > "HELLO" > > Another semantic marker here is 'do'. do in Clojure implies side- > effects. Since you can't uppercase a string by side effect, doto isn't > the right tool for this job. > > doto can't throw an error here or elsewhere when used on an immutable > object because: > > a) It can't generally know which objects are immutable > b) Even immutable objects may have methods with other side-effects > > Rich That makes sense. Thanks everyone for all the help. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
toUpperCase on java.lang.String
Calling a java method on a string directly works. user=> (.toUpperCase "hello") "HELLO" user=> (class "hello") #=java.lang.String But if I do this in a doto, it doesn't seem to work but I don't get any error message. user=> (doto (new java.lang.String "hello") (toUpperCase)) "hello" user=> (class (new java.lang.String)) #=java.lang.String Shouldn't this be working? If this is (by design) because strings are immutable (so no doto) shouldn't there be an error message? What am I missing here. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: primitive meta data
On Oct 15, 8:34 am, Islon <[EMAIL PROTECTED]> wrote: > Hi. > > I've made a dumb (very dumb) performance comparison function just to play > with the language. > I wanted to mark some symbols with a float primitive type but the compiler > complained so I had to annotate it with the Float class. > Here is the function: > > (defn dumb-test [] > (let [#^Float f2 567.09723] > (loop [#^Float f 1.8, i 1000] > (if (zero? i) > f > (recur (/ f f2) (dec i)) > > And the test: > > (loop [i 50] > (time (dumb-test)) > (if (zero? i) > i > (recur (dec i > > There's a way to put a float primitive type in the metadata to prevent the > Float -> float unboxing? > Feel free to point some mistakes I probably made, I've just started learn > clojure. > > The clojure version took an average: "Elapsed time: 217.833342 msecs" in my > machine. The following was somewhat faster. (defn dumb-test [] (let [f2 (float 567.09723)] (loop [f (float 1.2), i (long 1000)] (if (zero? i) f (recur (/ f f2) (dec i)) I get about 59ms on my machine. user=> (time (dumb-test)) "Elapsed time: 59.245176 msecs" 0.0 Parth > > The java version (below) took average 23 msecs: > > private static float dumbTest() { > float f = 1.8f; > float f2 = 567.09723f; > for(int i = 0; i < 1000; i++) { > f /= f2; > } > return f; > } > > Regards. > Islon --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: GUIs in Clojure
On Oct 9, 6:11 am, "Stephen C. Gilardi" <[EMAIL PROTECTED]> wrote: > On Oct 8, 2008, at 6:19 PM, Michael Beauregard wrote: > > Possibly of interest for the layout part of that, I recently checked > in clojure.contrib.miglayout which provides support for using > MiGLayout (http://miglayout.com) from Clojure. It removes some of the > repetitive code from the task of populating a JPanel and providing > constraints for miglayout. > Thanks for this Steve. This is definitely useful. I look forward to using this functionality more. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Creating a n-length vector filled with zeroes?
On Oct 8, 8:35 am, CuppoJava <[EMAIL PROTECTED]> wrote: > Hi, > I'm very new to clojure, and I'm just wondering what's the most > efficient way of creating a vector of zeroes. This is one way. user=> (vec (replicate 10 0)) [0 0 0 0 0 0 0 0 0 0] also user=> (into [] (replicate 10 0)) [0 0 0 0 0 0 0 0 0 0] At the REPL you could use (doc ) to get help on the function. There are a bunch of these useful functions like repeat, replicate, repeatedly etc. Parth > > This is my current code: > (loop [row [] > i 0] > (if (= i cols) > row > (recur (assoc row i 0) (inc i > > It looks pretty bad to me. My java code is more terse than this. > Thanks for your help. > -Cuppo --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: What "reasoner"?
Josip Gracin wrote: > Hi! > > Rich, in the Boston talk you mentioned that you're considering some > kind of a "reasoner" (if I understood correctly) for working with > databases. You also mentioned a project whose name sounded like "ios > reasoner". I can't find references on anything spelled "ios > reasoner". Could you tell me the actual name of the project. Thanks! I think it was the iris-reasoner datalog, also mentioned on IRC here: http://clojure-log.n01se.net/date/2008-10-02.html#14:45 http://iris-reasoner.org/ Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: slurp is in Clojure, but spit is in Contrib?
On Oct 6, 6:40 pm, Stuart Halloway <[EMAIL PROTECTED]> wrote: > Hi all > > For consistency, I would like to see spit moved into the boot.clj. > > This will play well with the Java crowd. For years I have poked fun of > Java for having megabytes of core library and no simple way to save a > file. This would be a nice addition in my view. It will be especially useful for people from non-java background coming to Clojure. I know I was quite confused about how to write to a file when I was ramping up on Clojure. Parth > > Stuart --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: safe navigation operator
On Oct 6, 7:00 pm, Rich Hickey <[EMAIL PROTECTED]> wrote: > On Oct 6, 9:36 am, Stuart Halloway <[EMAIL PROTECTED]> wrote: > > > > > Yes, that's better. Glad you like the idea. > > > Does anybody not named Stuart also want to see this added to > > Clojure? ;-) > > > Stuart > > > > On Oct 3, 3:13 pm, Stuart Halloway <[EMAIL PROTECTED]> wrote: > > >> (defmacro ?. > > >> "like .. but drops out on null object" > > >> ([x form] > > >> `(. ~x ~form)) > > >> ([x form & more] > > >> `(if-let x# (. ~x ~form) (.? x# [EMAIL PROTECTED] > > > > Interesting -- I like it. It doesn't seem to be totally compatible > > > with "..", though: > > > > user=> (?. System (getenv "SHELL") (startsWith "/bin") getClass > > > getName) > > > java.lang.Exception: Unable to resolve symbol: startsWith in this > > > context (NO_SOURCE_FILE:62) > > > > Also, if-let could give the wrong result in the (admittedly unlikely) > > > situation that one of the methods returns Boolean.FALSE. > > > Here's another take: > > > > (defmacro ?.. > > > "like .. but stops and returns nil if any method returns nil" > > > ([x form] > > > `(.. ~x ~form)) > > > ([x form & more] > > > `(let [x# (?. ~x ~form)] > > > (if (nil? x#) nil > > > (?. x# [EMAIL PROTECTED]) > > > > user=> (?.. System (getenv "SHELL") (startsWith "/bin") getClass > > > getName) > > > "java.lang.Boolean" > > > user=> (?.. System (getenv "FOO") (startsWith "/bin") getClass > > > getName) > > > nil > > I'm not opposed, but we'll need to find another name. Leading ? is a > likely candidate for rule syntax, and trailing means predicate. This construct will be very useful. How about the name "maybe" or similar along the lines of Haskell "Maybe" http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html Parth > > .?. > > ? > > Rich --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Collection Building Idiom
On Sep 19, 5:49 am, Mark McGranaghan <[EMAIL PROTECTED]> wrote: > Hi all, > > I was wondering if there was an idiomatic functional way to accomplish > the following: > > We have some parameters, and we want to build a collection based on > those parameters. The collection could have as many as n items, and > whether and what items get added for each of the n possibilities will > depend on the parameters. > > In Ruby, this might look like: > def build_coll(a, b) > coll = [] > if a > 2 > coll << (a * b) > end > if b > 2 > coll << (a + b) > end > if a > b > coll << (a - b) > end > coll > end > > build_coll(3, 1) > > I'd like to accomplish this using a purely functional style. One way > to do this would be to reduce a collection of test functions with an > initial empty collection and a reduce function that adds the result of > the test element if the test passes: > > (defn build-coll [a b] > (reduce > (fn [coll f] (if-let result (f a b) (conj coll result) coll)) > [] > [(fn [a b] (if (> a 2) (* a b))) > (fn [a b] (if (> b 2) (+ a b))) > (fn [a b] (if (> a b) (- a b)))])) > > (build-coll 3 1) > > Does anyone have any better ideas about how to go about this? Hi Mark, Not sure if this is better but here is another way to do it. (defn simple-build-coll [a b] (vec (filter #(not (nil? %)) (list (when (> a 2) (* a b)) (when (> b 2) (+ a b)) (when (> a b) (- a b)) user=> (simple-build-coll 3 1) [3 2] The vec is just to convert the collection to a vector if thats whats being used. If this is commonly needed in the program I would probably write a macro to do this. Its would make the program much more readable .. not the macro but the usage of it :) (defn reverse-pairs [l] (apply concat (reverse (partition 2 l (defmacro conj-if-aux [coll & preds_xs] (if preds_xs `(if ~(first preds_xs) (conj (conj-if-aux ~coll ~@(rest (rest preds_xs))) ~(second preds_xs)) (conj-if-aux ~coll ~@(rest (rest preds_xs coll)) (defmacro conj-if [coll & preds_xs] `(conj-if-aux ~coll ~@(reverse-pairs preds_xs))) The main logic is in conj-if-aux. I use reverse-pairs and conj-if just to maintain the correct order in the resulting collection (for lists and vectors). If thats not important conj-if-aux should suffice. reverse-pairs maintains the pairs of predicate and exprs in the reversed list. user=> (reverse-pairs [:a :b :c :d :e :f]) (:e :f :c :d :a :b) Usage would be: (defn mac-build-coll [a b] (conj-if [9 10] (> a 2) (* a b) (> b 2) (+ a b) (> a b) (- a b))) (defn mac-build-coll2 [a b] (conj-if '(9 10) (> a 2) (* a b) (> b 2) (+ a b) (> a b) (- a b))) user=> (mac-build-coll 3 1) [9 10 3 2] user=> (mac-build-coll2 3 1) (2 3 9 10) user=> Note that (1) the type of collection is maintained by conj here (either a list or a vector) and (2) the order in which elements are added depend on the the type of collection. Conj appends to head of list. 9,10 are used for the initial collection (either vector or list). Parth > > Thanks, > - Mark McGranaghan --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: 20080916 Release
On Sep 16, 7:00 pm, Rich Hickey <[EMAIL PROTECTED]> wrote: > http://sourceforge.net/project/showfiles.php?group_id=137961 > > Added: validators for vars/refs/agents, delay/force, isa-based > multimethods and a la carte hierarchies, require/use/load, namespace > aliases and many more functions and fixes. > > Special thanks to Chas Emerick, Graham Fawcett, Stephen C. Gilardi, > Chris Houser and Stuart Sierra for their contributions, and to > everyone here for your suggestions and bug reports. > > More details at: > > http://clojure.blogspot.com/2008/09/20080916-release.html > > Rich Very cool. :) Thanks Rich and the all Clojure contributors. This is truly a fantastic language and it keeps getting better. I love using it. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Debian package for clojure
On Sep 11, 6:22 pm, "Paul Stadig" <[EMAIL PROTECTED]> wrote: > I have created a debian package for clojure. I've basically packaged > up the JAR with the bin script > fromhttp://github.com/jochu/clojure-extra/tree/master. It's still a > work-in-progress, but if there are any debian users out there, I'd > like feedback. To install the debian package you need to first add the > following line to your apt sources: > > debhttp://ppa.launchpad.net/pjstadig/ubuntuhardy main > > Then just do an apt update and "sudo apt-get install clojure" and it > should work for you (*fingers crossed*). You can find my GPG key out > in the ether ([EMAIL PROTECTED]) to verify the installation, whether > you *trust* me is another issue ("Who is this guy?!"). ;) This deb was > actually built on Ubuntu. I think it'll work on any debian based > distribution, but I'm a newb at this, so please send me your feedback. > > This project raises (at least) two issues: > > 1. How can we get this into the standard debian distribution? It is my > understanding that someone has to be (or become) an official debian > developer to get it into the distribution. I'm willing to pursue that > unless someone else is already there. > > 2. How should this be maintained/expanded? I am willing to contribute > the debian build files back to clojure (it just adds a debian > directory with some files in it). However, some of the things that are > part of the debian build should probably be integrated into the main > project and build file (man pages, bin scripts, etc.), because there > may be other distributions that could reuse some of those files. > Additionally, this could all be expanded to include bin scripts and > such for Windows, too. If we're not going to merge this back into the > main source (or if we don't want to do it yet), I could setup a GitHub > project to maintain the debian build system separately. > > Any thoughts on all this? > Hi Paul, As a debian user I really like the idea for having a Clojure deb. This is generally my preferred method for installing software on debian and was the first thing I looked for. Regarding, 2, as already mentioned by you it would be nice if the clj script + some man pages could go in. It would definitely make life easier, especially for new user. Perhaps, Rich can comment on rolling some of these into the trunk. Can rlwrap be marked as a deb package dependency for clj script? this will ensure that the base interactive shell installation works with tab-completion and stuff. Currently, I use Clojure from svn as it gets me the latest and greatest feature set :) Are you planning to pull from svn at a certain frequency (1 a fortnight?) or to stick to the official releases? I suppose once Clojure goes 1.0, at that point you could stick to the latest stable release. Maybe we could have the following packages: clojure clojure-doc - this could be txt files generated from the deb release clj-vim - VimClojure clj-emacs - emacs + slime stuff My 2c. Thanks for this. Parth > Paul --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: local functions?
On Sep 11, 3:01 am, Allen Rohner <[EMAIL PROTECTED]> wrote: > > For very short functions one can use the cut notation: #(...). In case > > there are several functions or functions going over several lines, this > > is a sign that they should go into an own defn(-) with appropriate > > docstring. > > Maybe the solution is to use defn-. Scheme made me used to the local > function approach for encapsulation. I don't have a problem with doing > > (defn foo [x] > (defn bar [y] > ) > (defn baz [z]) > (do_stuff (bar[x])) > > except that the interior defns are public. I like the idea. defn- would also work like this but that won't prevent bar and baz from being used inside the package itself. (let [foo (fn [x] ...)] (foo 42)) Does tend to get a little ugly if fn grows more than a line or two. Not sure how it can be done though. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: ns usage for multiple clj files
On Sep 7, 1:00 pm, Meikel Brandmeyer <[EMAIL PROTECTED]> wrote: > I think your problems should be solved now, since in my understanding > they arise due to the non-adherence to the required file layout.> > java.io.FileNotFoundException: Could not locate Clojure resource > > on classpath: bar/mycode/test.clj > > ^^^ > load-resources works namespace directory relative for relative > pathnames! > Thanks for the pointers Meikel. I was finally able to get it to work. I had missed one of the points in the docs for load-resources: "A path is interpreted as classpath-relative if it begins with a slash or relative to the root directory for the current namespace otherwise" Apart from trying the bar namespace approach mentioned I also cleaned up my 'mycode' example. I added a symlink to mycode in ~/.clj which I added to the classpath. And updated the code below which works. --- test.clj start (in-ns 'mycode) (defn foo [] :foo-called) --- test.clj end --- --- mycode.clj start --- (ns mycode (:refer-clojure) (:load-resources "test.clj")) --- mycode.clj end --- --- interaction start user=> (load-resources "/mycode/mycode.clj") nil user=> (mycode/foo) :foo-called user=> --- interaction end Parth > smime.p7s > 5KViewDownload --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
ns usage for multiple clj files
Hello, I am trying to use the latest ns/in-ns functionality from HEAD. I don't seem to be getting it right. Here is what I am tring to do. 1. test.clj - contains a function foo 2. tst-pkg.clj - contains the ns definition (so I can get my dependencies right in a multi-file project). I am assuming all loads for 'ns' happen sequentially. I put these in $HOME/code/mycode. I create a directory $HOME/.clj/user and softlink $HOME/code/mycode into this. $HOME/.clj/user is in the classpath. Contents of the files below: --- test.clj start --- (in-ns 'bar) (clojure/defn foo [] :foo-called) --- test.clj end --- --- tst-pkg.clj start --- (ns bar (:refer-clojure) (:load-resources "mycode/test.clj")) --- tst-pkg.clj end --- If I load-resources test.clj directly it works. user=> (load-resources "mycode/test.clj") nil user=> (bar/foo) :foo-called user=> However, when I try to either load-file or load-resources tst-pkg.clj I get errors. [parth:~/code/mycode]% clj Clojure user=> (load-resources "mycode/tst-pkg.clj") java.io.FileNotFoundException: Could not locate Clojure resource on classpath: bar/mycode/test.clj java.io.FileNotFoundException: Could not locate Clojure resource on classpath: bar/mycode/test.clj at clojure.lang.RT.loadResourceScript(RT.java:365) at clojure.lang.RT.loadResourceScript(RT.java:347) at clojure.lang.RT.loadResourceScript(RT.java:339) at clojure.load_resources__1744.doInvoke(boot.clj:3209) at clojure.lang.RestFn.invoke(RestFn.java:413) at user.eval__2286.invoke(tst-pkg.clj:1) at clojure.lang.Compiler.eval(Compiler.java:3850) at clojure.lang.Compiler.load(Compiler.java:4151) at clojure.lang.RT.loadResourceScript(RT.java:360) at clojure.lang.RT.loadResourceScript(RT.java:347) at clojure.lang.RT.loadResourceScript(RT.java:339) at clojure.load_resources__1744.doInvoke(boot.clj:3209) at clojure.lang.RestFn.invoke(RestFn.java:413) at user.eval__2283.invoke(Unknown Source) at clojure.lang.Compiler.eval(Compiler.java:3850) at clojure.lang.Repl.main(Repl.java:75) user=> (load-file "/home/parth/code/mycode/tst-pkg.clj") java.io.FileNotFoundException: Could not locate Clojure resource on classpath: bar/mycode/test.clj java.io.FileNotFoundException: Could not locate Clojure resource on classpath: bar/mycode/test.clj at clojure.lang.RT.loadResourceScript(RT.java:365) at clojure.lang.RT.loadResourceScript(RT.java:347) at clojure.lang.RT.loadResourceScript(RT.java:339) at clojure.load_resources__1744.doInvoke(boot.clj:3209) at clojure.lang.RestFn.invoke(RestFn.java:413) at user.eval__2292.invoke(tst-pkg.clj:1) at clojure.lang.Compiler.eval(Compiler.java:3850) at clojure.lang.Compiler.load(Compiler.java:4151) at clojure.lang.Compiler.loadFile(Compiler.java:4118) at clojure.lang.RT$3.invoke(RT.java:289) at user.eval__2289.invoke(Unknown Source) at clojure.lang.Compiler.eval(Compiler.java:3850) at clojure.lang.Repl.main(Repl.java:75) user=> What am I doing wrong here? Thanks. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: clojure/ns and gen-and-save-class
On Sep 6, 12:23 am, Rich Hickey <[EMAIL PROTECTED]> wrote: > On Sep 5, 7:06 am, Christopher Taylor <[EMAIL PROTECTED]> wrote: > > > > > Hi, > > > this is my first post to the list (though I've been lurking for a > > while) and I'm not yet actively working with Clojure, so take what I > > say here with a grain of salt :). > > > On Sep 4, 2008, at 3:28 PM, Rich Hickey wrote: > > > > On Sep 3, 7:51 pm, Rich Hickey <[EMAIL PROTECTED]> wrote: > > >> On Sep 3, 5:14 pm, Chouser <[EMAIL PROTECTED]> wrote: > > > >>> On Wed, Sep 3, 2008 at 4:36 PM, Stephen C. Gilardi > > >>> <[EMAIL PROTECTED]> wrote: > > > >>>> I saw some discussion of how to fix this on the IRC log but I > > >>>> can't get on > > >>>> at the moment. > > >>>> It looks like the current plan is to change "ns" to remove the > > >>>> sensitivity > > >>>> to "the namespace is already defined" and add "(:refer- > > >>>> clojure ...)" to the > > >>>> list of supported reference arguments. > > > >>> Well, here's a patch for the behavior discussed on IRC. I'm posting > > >>> it only because it's complete and working, not in any attempt to > > >>> stifle further discussion. If we settle on any alternate solution, > > >>> this patch can just be ignored. > > > >> I think the only problem is in the case of subsequent use of ns. I > > >> originally envisioned the 'main' .clj file doing an involved ns and > > >> subsequent files just doing (ns foo), as well as the use of ns at the > > >> repl to change namespaces. Now, if you did > > > >> (ns foo (:refer-clojure ...) ...) > > > >> any later (ns foo) is going to bring in all of clojure. I'd prefer it > > >> did nothing but change *ns*. > > > > After sleeping on it, I think what we have been calling ns should be > > > called defns instead, and ns should just set *ns*. Thus there should > > > be only one defns for any particular namespace, and (ns foo) can be > > > used to set the namespace for a file and/or change the namespace at > > > the repl. > > > > Thoughts? > > > So, if I understand this correctly, you'd have a file myns/myns.clj > > containing (defns myns) along with :require and/or :use clauses for > > the dependencies of the whole ns. Other files under myns/ would > > contain just the statement (ns myns). > > Right. > > > Personally, from a separations-of-concerns standpoint, I'd prefer if > > every file were responsible for getting access to all the libs it needs. > > Being an interactive language, hanging such dependencies on files > doesn't really work, since bits and pieces of things originally > defined in files might be fixed/redefined in the repl etc. So the unit > of reference is the namespace, and all code in the same namespace > shares the same references and name resolution. This aids > introspection as well. > > > Oh, one (tiny) niggle wrt the name "defns": it looks a bit like the > > plural form of "defn", so it might be confused with defmulti or > > something that defines a bunch of functions at once. > > I didn't think about the plural angle - anyone else bothered by that? > The alternative is defnamespace. > I like the idea of having a defxxx to define a name space as its consistent with the rest of the API. Thanks Rich. Regarding the name, actually, I didn't realize plural angle till it was pointed out. However, I feel defns is a good enough name as there isn't a 's' being used for plural by any of the other defs to my knowledge. If a need arises to use s for plurals in some future def it may become confusing. defnamespace will make be inconsistent with 'ns', 'in-ns' etc. Putting a - as 'def-ns' will also make it somewhat different from the other defs IMHO. Parth > Rich --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: avoiding duplication using multi-methods
On Sep 1, 12:26 pm, [EMAIL PROTECTED] wrote: > On Aug 31, 8:48 pm, Parth Malwankar <[EMAIL PROTECTED]> wrote: > > > > > Hello, > > > I have a situation in which different multi-methods > > need similar behavior with different arguments. > > > So they call the same function (one-or-two below) > > with the arguments. E.g. > > > (defmulti what-num (fn [x] x)) > > > (defn one-or-two [x] (println "saw one or two: " x)) > > > (defmethod what-num :one [x] (one-or-two x)) > > (defmethod what-num :two [x] (one-or-two x)) > > (defmethod what-num :three [x] (println "saw 3")) > > (defmethod what-num :four [x] (println "saw 4")) > > > user=> (what-num :one) > > saw one or two: :one > > nil > > user=> (what-num :two) > > saw one or two: :two > > nil > > user=> (what-num :three) > > saw 3 > > > This works fine. However, I was wondering if its at all > > possible to return duplication of creating the > > methods 'what-num :one [x]' and 'what-num :two [x]'. > > > Can we have something to the effect of > > 'what-num (or :one :two) [x]'? This would help get > > rid of one-or-two and I would be able to define a single > > what-num for this. > > > I could have 'defmulti what-num' conditionally return > > something like :one-or-two but I am not sure if thats such > > a good idea as I might end up with a big 'cond' over > > time. > > > What would be a good way to do something like this? > > I don't know if it is a "good" way, but here is what I used for a > similar problem: > > (defmacro defmethod-for-values > [multifn dispatch-values-seq & fn-tail] > `(let [pvar# (var ~multifn) > method# (fn [EMAIL PROTECTED])] > (doseq dispatch-val# ~dispatch-values-seq > (. pvar# (commuteRoot (fn [#^clojure.lang.MultiFn mf#] > (. mf# > (assoc dispatch-val# method# > Thanks Darren. Along the lines of your macro I created the one below that avoids clojure.lang.*. I keep forgetting this is lisp and we can write a macro :P Here is what I could come up with. (defmulti what-num (fn [x] x)) (defmacro defmethod-in [n dval-coll args & body] (let [get-method (fn [d] `(defmethod ~n ~d ~args [EMAIL PROTECTED]))] `(do ~@(map get-method dval-coll (defmethod-in what-num [:one :two] [x] (println "1 or 2" x)) (defmethod what-num :three [x] (println "saw 3")) (defmethod what-num :four [x] (println "saw 4")) (defmethod what-num :default [x] :default) In case this can be improved further, comments welcome. Seems to be working fine so far: user=> (what-num :four) saw 4 nil user=> (what-num :one) 1 or 2 :one nil user=> (what-num :two) 1 or 2 :two nil user=> (what-num :three) saw 3 nil user=> (what-num :five) :default Parth > Which is just a wrapper around the defmethod macro that allows you to > specify a list of values instead of a single value that will be mapped > to the method. > > This would allow you to define your above example with: > > (defmulti what-num (fn [x] x)) > > (defmethod-for-values what-num '(:one :two) [x] (println "saw one or > two: " x)) > (defmethod what-num :three [x] (println "saw 3")) > (defmethod what-num :four [x] (println "saw 4")) > > See this thread for more details: > > http://groups.google.com/group/clojure/browse_thread/thread/eed9015c2... > > Hope this helps, > --Darren --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
avoiding duplication using multi-methods
Hello, I have a situation in which different multi-methods need similar behavior with different arguments. So they call the same function (one-or-two below) with the arguments. E.g. (defmulti what-num (fn [x] x)) (defn one-or-two [x] (println "saw one or two: " x)) (defmethod what-num :one [x] (one-or-two x)) (defmethod what-num :two [x] (one-or-two x)) (defmethod what-num :three [x] (println "saw 3")) (defmethod what-num :four [x] (println "saw 4")) user=> (what-num :one) saw one or two: :one nil user=> (what-num :two) saw one or two: :two nil user=> (what-num :three) saw 3 This works fine. However, I was wondering if its at all possible to return duplication of creating the methods 'what-num :one [x]' and 'what-num :two [x]'. Can we have something to the effect of 'what-num (or :one :two) [x]'? This would help get rid of one-or-two and I would be able to define a single what-num for this. I could have 'defmulti what-num' conditionally return something like :one-or-two but I am not sure if thats such a good idea as I might end up with a big 'cond' over time. What would be a good way to do something like this? Thanks. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: debugging, logging, ... and code sections
Frantisek Sodomka wrote: > Hello! > It is very common pattern to include parts of code which are used for > specific purposes - for example debugging, logging, etc. While these parts > can be used when developing code, they can be removed from finished > application. One way is to comment these parts out, when we are done. > Since commenting can be tedious and error-prone, it makes sense to make a > macro for this: > > (def *debug* true) ; true/false > > (defmacro debug [& body] >(if *debug* > `(do [EMAIL PROTECTED]))) > > > (defn myfn [x] >(debug > (println "Print some debug info...") > (print "x = ") (prn x)) >(* 2 x)) > > (myfn 5) > > > To extend this idea little further, lets define "code sections": > > (def *section-tags* {:debug true :log0 true :log1 false}) > > (defmacro section [tag & body] >(if (*section-tags* tag) > `(do [EMAIL PROTECTED]))) > > > (defn myfn [x] >(section :debug > (println "debugging info...") > (print "x = ") (prn x)) >(section :log0 > (println "logging info...")) >(section :log1 > (println "detailed logging info...")) >(* 2 x)) > > (myfn 10) > > > Latest addition for libs to boot.clj also has this pattern, when using > *loading-verbosely* flag. > > Any comments welcome, Frantisek I like something along the lines of Python decorators[1] as that keeps the logic of the function from being lost in the instrumentation code. E.g. (def *verbose* true) (defn print-decorate [f] (fn [& args] (println f "called with" args) (apply f args))) (defn foo [x] (* 2 x)) (when *verbose* (def foo (print-decorate foo))) With *verbose* true: user=> (load-file "foo.clj") #'user/foo user=> (foo 2) [EMAIL PROTECTED] called with (2) 4 With *verbose* false: user=> (load-file "foo.clj") nil user=> (foo 2) 4 Perhaps this approach can be improvised further but I myself am somewhat of a Clojure noob. I suspect the boot.clj code (especially in the early part of the file) may not be most ideomatic Clojure code as Clojure is still booting itself. On a somewhat related note. Getting the function name at the Clojure prompt seems to work: user=> (:name (meta (var foo))) foo However if I try to improvise print-decorate by putting in the above approach, I get an exception while loading the file. (defn print-decorate [f] (fn [& args] (println (:name (meta (var f))) "called with" args) (apply f args))) clojure.lang.Compiler$CompilerException: foo.clj:5: Unable to resolve var: f in this context Could someone explain what I am doing wrong here? How can I get the function name at runtime in print-decorate? Full exception log below. Parth [1] http://www.ibm.com/developerworks/linux/library/l-cpdecor.html user=> (load-file "foo.clj") java.lang.Exception: Unable to resolve var: f in this context clojure.lang.Compiler$CompilerException: foo.clj:5: Unable to resolve var: f in this context at clojure.lang.Compiler.analyzeSeq(Compiler.java:3821) at clojure.lang.Compiler.analyze(Compiler.java:3654) at clojure.lang.Compiler.analyze(Compiler.java:3627) at clojure.lang.Compiler.access$100(Compiler.java:37) at clojure.lang.Compiler$InvokeExpr.parse(Compiler.java:2630) at clojure.lang.Compiler.analyzeSeq(Compiler.java:3816) at clojure.lang.Compiler.analyze(Compiler.java:3654) at clojure.lang.Compiler.analyze(Compiler.java:3627) at clojure.lang.Compiler.access$100(Compiler.java:37) at clojure.lang.Compiler$InvokeExpr.parse(Compiler.java:2630) at clojure.lang.Compiler.analyzeSeq(Compiler.java:3816) at clojure.lang.Compiler.analyze(Compiler.java:3654) at clojure.lang.Compiler.analyze(Compiler.java:3627) at clojure.lang.Compiler.access$100(Compiler.java:37) at clojure.lang.Compiler$InvokeExpr.parse(Compiler.java:2630) at clojure.lang.Compiler.analyzeSeq(Compiler.java:3816) at clojure.lang.Compiler.analyze(Compiler.java:3654) at clojure.lang.Compiler.analyze(Compiler.java:3627) at clojure.lang.Compiler.access$100(Compiler.java:37) at clojure.lang.Compiler$BodyExpr$Parser.parse(Compiler.java: 3340) at clojure.lang.Compiler$FnMethod.parse(Compiler.java:3187) at clojure.lang.Compiler$FnMethod.access$1200(Compiler.java: 3098) at clojure.lang.Compiler$FnExpr.parse(Compiler.java:2729) at clojure.lang.Compiler.analyzeSeq(Compiler.java:3812) at clojure.lang.Compiler.analyze(Compiler.java:3654) at clojure.lang.Compiler.analyzeSeq(Compiler.java:3804
generating clj docs
Hello, I have uploaded a script gen-clj-docs.clj in the file area that goes through all the clojure and clojure-contrib modules and dumps out the latest docs from sources as txt files. It leverages clojure.contrib.ns-utils for this (thanks!). Thought that some people might find this useful. http://groups.google.com/group/clojure/web/gen-clj-docs.clj Note that its best to run this in a separate folder as it creates 1 txt file for each ns. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: The ant simulation
On Aug 30, 7:52 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > In the ant simulation the world function looks like this > > (def world > (apply vector > (map (fn [_] > (apply vector (map (fn [_] (ref (struct cell 0 0))) > (range dim > (range dim > > I'm not sure why the calls to '(apply vector' are required. I have two > theories: > > * It is to work round the lazy nature of map and force the creation of > all of the refs. If this is the case, can anyone enlighten me as to > why this might be necessary? > * It is a performance optimisation to make lookups of faster later. > > A third theory is that neither of the above theories is correct. > > Can anyone provide me with some insight? vector takes individual elements as arguments and map returns a list. If we simply (vector (map ..)) the entire list returned by map is seen as a single element. Hence 'apply'. user=> (vector 1 2 3) [1 2 3] user=> (map inc [1 2 3]) (2 3 4) user=> (vector (map inc [1 2 3])) [(2 3 4)] user=> (apply vector (map inc [1 2 3])) [2 3 4] user=> Parth > > Thanks, > > Rob Lally. --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Google Code?
On Aug 30, 6:53 pm, Rich Hickey <[EMAIL PROTECTED]> wrote: > Google has recently opened up Google Code to hosting projects using > the Eclipse Public License, the successor to the CPL used by Clojure. > > Right now I'm only using SF for SVN, as the web interface on SF for > anything else is quite cumbersome. I could easily move to EPL for > Clojure, making hosting at Google Code a possibility, and am > interested in feedback from anyone who has hosted at Google Code or > participated in a project that did. I was hosting a mini project on google code till a few day back (I deleted it as I had not touched it in about 2 months). I am not sure about your overall criteria but here are some things that I liked about it. - While the 'issue tracker' is not a full fledged bug tracking system like bugzilla, I liked it for its responsiveness and simplicity. Its trivial to add new categories and stuff. - Overall responsiveness (svn, wiki etc.) was really good. - project creation was trivial. - Viewing of changelogs, diffs etc. are possible via the web interface - Good integration - wiki, issue tracker, download area, links marked 'featured' automatically show up on front page (same with 'featured' downloads). I think the focus for google code has been on performance and ease of use which I liked. I had also evaluated launchpad with its bzr integration but as a user I found googlecode easier to use and also to administer. One thing to note is that they had a 100MB disk space quota (which they apparently increase once you file a ticket - I saw a bunch of such tickets closed in the logs though I personally didn't hit this limit). Personally I would vote for googlecode. Parth > > Thanks, > > Rich --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: New Release of VimClojure: v1.2.0
On Aug 30, 5:53 pm, Parth Malwankar <[EMAIL PROTECTED]> wrote: > On Aug 30, 3:35 am, Meikel Brandmeyer <[EMAIL PROTECTED]> wrote: > > > Please test this release since it is due for upstream inclusion in Vim. > Sorry for the double post. Just wondering if you have seen/used the lisp_rainbow support in Vim for CL. Basically it highlights each paren pair in a separate color upto 10 levels. If that is at all possible it will be _really_ cool. See. :h ft-lisp-syntax in vim. Thanks. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: New Release of VimClojure: v1.2.0
On Aug 30, 3:35 am, Meikel Brandmeyer <[EMAIL PROTECTED]> wrote: > Dear Clojurians, > > a new version of VimClojure is available. I tried to fix also the string > handling for the indenting. This should work now. Please note that there > is still some issue with a line ending in a comment containing a (. I'm > not sure how to fix this. > > New in this release: > > - I further refined the highlighting. The standard highlighting groups > are now used. Eg. Function, Macro, etc. > > - The highlighting now uses the "default" flag to make them overridable > by the user. > > - The highlighting synchronises with empty lines. (Stolen from > scheme.vim) > > - The 'define' option is now used. This let's you eg. jump to the > definition of the word under the cursor. > > - As already mentioned: fixed issue with indenting and multi-line > strings. > > Please test this release since it is due for upstream inclusion in Vim. > Thanks Meikel. The syntax highlighting seems much improved from the earlier release. Just found one minor issue. defmulti formatting is like: (defmulti foo :abc [n] (println n)) With (pr.. being aligned with foo instead of ^(d. You might also want to update the completions list as a bunch of stuff has been added in the last few days (lib support, get-in, printf etc) Looking forward to seeing clj being supported by vim by default :) Will let you know if I come across something else. Parth > The release may be found at the usual place: > http://kotka.de/projects/clojure/vimclojure.html > > Sincerely > Meikel > > smime.p7s > 5KViewDownload --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: updating nested structure
On Aug 28, 8:08 pm, Rich Hickey <[EMAIL PROTECTED]> wrote: > On Aug 27, 10:37 pm, Parth Malwankar <[EMAIL PROTECTED]> > wrote: > > > > > On Aug 28, 12:10 am, Rich Hickey <[EMAIL PROTECTED]> wrote: > > > > I posted a variant here: > > > >http://paste.lisp.org/display/65964 > > > Rich, > > > It works very nicely. Thanks. > > > Just one thought in case the functions args are still being > > decided on. Could we consider taking access path as a > > vector rather than directly as function args. > > > Here is the use case I have in mind. > > > I think most access paths [:a :b :c] would be generated. > > Nested structures would be something like > > > processor -> GPRs (general purpose regs) -> r0 r1 .. rN > > -> FPRs (floating point regs) -> f0 f1 .. fN > > > fridge -> fruits -> apple mango ... > > -> veggies -> eggplant ... > > -> diary -> milk yoghurt ... > > > So the developer may set up something like a > > (fridge-item-path (get-fruit)) => [:fruits :apple] > > (processor-reg-path (get-reg-arg-from-instruction)) => [:gpr-set :r0] > > > With the current arg handling this is what we would need to do: > > > user=> (item-path :mango) > > [:fruits :mango] > > > user=> (apply mk-get my-fridge (conj (item-path :mango) :quantity)) > > 30 > > > user=> (apply mk-assoc my-fridge (conj (item-path :mango) :quantity > > 40)) > > {:fruits {:mango {:quantity 40, :color :yellow}, > > :apple {:quantity 20, :color :red}}, > > :diary-products {:milk {:quantity 1, :color :white, > > :type :low-fat}, > > :yoghurt {:quantity 10, :color :pink, > > :type :strawberry}}} > > > [formatting added above for readability] > > > In case the access path were vectors the above could become: > > > (mk-get my-fridge (item-path :mango) :quantity) > > (mk-assoc my-fridge (item-path :mango) :quantity new-quantity) > > > Much less noise. > > I don't see this (partial path + separate last key) as a general way > of doing things. The only other way I would consider is the entire > path as a sequence: > > (defn mk-get [m ks] > (reduce get m ks)) > > (defn mk-assoc [m [k & ks] v] > (if ks > (assoc m k (mk-assoc (get m k) ks v)) > (assoc m k v))) > > ;usage > (def nx {:a {:b {:c {:content [1 10] :other 2) > > (mk-get nx [:a :b :c :content]) > -> [1 10] > > (mk-assoc nx [:a :b :c :content 0] 42) > -> {:a {:b {:c {:other 2, :content [42 10] > > (mk-assoc {} [:a :b :x] 42) > -> {:a {:b {:x 42}}} > Thanks Rich. Sounds like a good idea to me. Works beautifully. user=> (load-file "fruits.clj") #'user/my-fridge user=> (mk-get my-fridge (item-quantity-path :mango)) 30 user=> (mk-assoc my-fridge (item-quantity-path :mango) 50) {:fruits {:mango {:quantity 50, :color :yellow}, :apple {:quantity 20, :color :red}}, :diary-products {:yoghurt {:quantity 10, :color :pink, :type :strawberry}, :milk {:quantity 1, :color :white, :type :low-fat}}} user=> Parth > Rich --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: updating nested structure
On Aug 28, 8:13 am, Chouser <[EMAIL PROTECTED]> wrote: > On Wed, Aug 27, 2008 at 10:37 PM, Parth Malwankar > > <[EMAIL PROTECTED]> wrote: > > In case the access path were vectors the above could become: > > > (mk-get my-fridge (item-path :mango) :quantity) > > (mk-assoc my-fridge (item-path :mango) :quantity new-quantity) > > > Much less noise. > > apply actually can do the conj'ing for you: > > (apply mk-get my-fridge (item-path :mango) :quantity) I get an error with this. user=> (item-path :mango) [:fruits :mango] user=> (apply mk-get my-fridge (item-path :mango) :quantity) java.lang.IllegalArgumentException: Don't know how to create ISeq from: Keyword : :quantity java.lang.IllegalArgumentException: Don't know how to create ISeq from: Keyword : :quantity at clojure.lang.RT.seqFrom(RT.java:461) at clojure.lang.RT.seq(RT.java:444) at clojure.seq__28.invoke(boot.clj:92) at clojure.spread__132.invoke(boot.clj:357) at clojure.spread__132.invoke(boot.clj:358) at clojure.spread__132.invoke(boot.clj:358) at clojure.apply__135.doInvoke(boot.clj:364) at clojure.lang.RestFn.invoke(RestFn.java:460) at user.eval__2237.invoke(Unknown Source) at clojure.lang.Compiler.eval(Compiler.java:3847) at clojure.lang.Repl.main(Repl.java:75) user=> (apply mk-get my-fridge (conj (item-path :mango) :quantity)) 30 Is this supposed to work? If it does it will be very convenient. Parth > > --Chouser --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: updating nested structure
On Aug 28, 12:10 am, Rich Hickey <[EMAIL PROTECTED]> wrote: > I posted a variant here: > > http://paste.lisp.org/display/65964 > Rich, It works very nicely. Thanks. Just one thought in case the functions args are still being decided on. Could we consider taking access path as a vector rather than directly as function args. Here is the use case I have in mind. I think most access paths [:a :b :c] would be generated. Nested structures would be something like processor -> GPRs (general purpose regs) -> r0 r1 .. rN -> FPRs (floating point regs) -> f0 f1 .. fN fridge -> fruits -> apple mango ... -> veggies -> eggplant ... -> diary -> milk yoghurt ... So the developer may set up something like a (fridge-item-path (get-fruit)) => [:fruits :apple] (processor-reg-path (get-reg-arg-from-instruction)) => [:gpr-set :r0] With the current arg handling this is what we would need to do: user=> (item-path :mango) [:fruits :mango] user=> (apply mk-get my-fridge (conj (item-path :mango) :quantity)) 30 user=> (apply mk-assoc my-fridge (conj (item-path :mango) :quantity 40)) {:fruits {:mango {:quantity 40, :color :yellow}, :apple {:quantity 20, :color :red}}, :diary-products {:milk {:quantity 1, :color :white, :type :low-fat}, :yoghurt {:quantity 10, :color :pink, :type :strawberry}}} [formatting added above for readability] In case the access path were vectors the above could become: (mk-get my-fridge (item-path :mango) :quantity) (mk-assoc my-fridge (item-path :mango) :quantity new-quantity) Much less noise. Its not a big deal as the user would probably be writing a layer on top of mk-get/mk-assoc e.g. fridge-add-item fridge-check-item but then with access-paths as vectors it usage will be cleaner. If you think this is a common enough case it could be considered. Also, thanks for the [m [k & ks] v] destructuring trick. I didn't know we could do that. Very neat. Thanks very much. Parth > Rich --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: updating nested structure
On Aug 26, 8:25 pm, Parth Malwankar <[EMAIL PROTECTED]> wrote: > Hello, > > In order to update fields in nested structures/maps easily > I have created a macro 'field-write'. > (defmacro field-write [st k v access-spec] > ; st=data, k=key to update, v=val to put, access-spec=access > vector > ; ... code listing after interaction > > user=> nx > {:a {:b {:c {:content 10 > user=> (field-write nx :content 1000 [:a :b :c]) > {:a {:b {:c {:content 1000 > user=> (macroexpand '(field-write nx :content 1000 [:a :b :c])) > (clojure/assoc > nx :a > (clojure/assoc > (clojure/-> nx :a) :b > (clojure/assoc > (clojure/-> nx :a :b) :c > (clojure/assoc > (clojure/-> nx :a :b :c):content 1000 > > [formatting added above for readability] > > It seems to be working fine but I thought it may be > good to get inputs from the Clojure experts here to > see if there is a better way to do this in Clojure. > > (def nx {:a {:b {:c {:content 10) > > (def field-write) > (defmacro field-write [st k v access-spec] > ; st=data, k=key to update, v=val to put, access-spec=access > vector > (if (pred/empty? access-spec) > `(assoc ~st ~k ~v) > (field-write st (last access-spec) > `(assoc (-> ~st [EMAIL PROTECTED]) ~k ~v) > (butlast access-spec > After some more experimentation I found that the field-write macro didn't work with access-specs like (vector :a :b :c) ... I should have thought of that before. So I reimplemented field-read and field-write as functions which seem to work in all scenarios. (defn field-read [st as] "user=> nx {:a {:b {:c {:data 10 user=> (field-read nx [:a :b :c]) {:data 10}" (eval (reduce (comp reverse list) st as))) (defn field-write [structure kwd value access-spec] "user=> nx {:a {:b {:c {:data 10 user=> (field-write nx :data 20 [:a :b :c]) {:a {:b {:c {:data 20 user=> (field-write nx :data (+ 2 2 2) (vector :a :b :c)) {:a {:b {:c {:data 6" (loop [st structure k kwd v value as access-spec] (if (pred/empty? as) (assoc st k v) (recur st (last as) (assoc (field-read st as) k v) (butlast as) I suspect using eval in field-read is a bad idea (preformance?) but I couldn't come up with a better way to do it. access-spec needs to be a vector as its something thats returned by another function in my use case (otherwise I could have used it with ->). Can I do something better here? Comments? Thanks very much. Parth > Thanks. > Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
Re: Greetings
On Aug 26, 10:05 pm, noahr <[EMAIL PROTECTED]> wrote: > ps - any chance of getting a hold of that ant colony demo? http://clojure.googlegroups.com/web/ants.clj Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
path: some more error info for "Don't know how to create ISeq from..."
Hello, Attached is a patch to give a little more information for "java.lang.IllegalArgumentException: Don't know how to create ISeq from:" error. The current behavior is: user=> (map identity 1) java.lang.IllegalArgumentException: Don't know how to create ISeq from: Integer java.lang.IllegalArgumentException: Don't know how to create ISeq from: Integer . snipped with patch: user=> (map identity 1) java.lang.IllegalArgumentException: Don't know how to create ISeq from: Integer : 1 java.lang.IllegalArgumentException: Don't know how to create ISeq from: Integer : 1 snipped I found it a helpful to understand macro expansion errors better: user=> (macroexpand '(field-write-priv x :c 20 (vector :a :b))) java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol : G__2867 java.lang.RuntimeException: java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol : G__2867 at clojure.lang.LazyCons.rest(LazyCons.java:63) at clojure.lang.RT.printInnerSeq(RT.java:1320) ... snipped .. at clojure.lang.RT.print(RT.java:1173) at clojure.lang.Repl.main(Repl.java:76) Caused by: java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol : G__2867 at clojure.lang.RT.seqFrom(RT.java:461) ... snipped .. at clojure.lang.LazyCons.rest(LazyCons.java:59) ... 11 more (let* [G__2867 (vector :a :b)] (if (clojure.contrib.pred/empty? G__2867) (clojure/list (quote clojure/assoc) x :c 20) (user/field- write-priv x (clojure/last G__2867) (clojure/list (quote clojure/ assoc) (clojure/-> xuser=> java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol : G__2716 I am not a Java or Clojure expert so there may be a better way to do this. Patch follows. Parth [parth:~/src/clojure/src/jvm/clojure/lang]% svn update At revision 1006. [parth:~/src/clojure/src/jvm/clojure/lang]% svn diff RT.java Index: RT.java === --- RT.java (revision 1006) +++ RT.java (working copy) @@ -458,7 +458,7 @@ // else if(coll instanceof Enumeration) // return EnumerationSeq.create(((Enumeration) coll)); else - throw new IllegalArgumentException("Don't know how to create ISeq from: " + coll.getClass().getSimpleName()); + throw new IllegalArgumentException("Don't know how to create ISeq from: " + coll.getClass().getSimpleName() + " : " + coll.toString()); } static public ISeq keys(Object coll){ [parth:~/src/clojure/src/jvm/clojure/lang]% --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---
updating nested structure
Hello, In order to update fields in nested structures/maps easily I have created a macro 'field-write'. (defmacro field-write [st k v access-spec] ; st=data, k=key to update, v=val to put, access-spec=access vector ; ... code listing after interaction user=> nx {:a {:b {:c {:content 10 user=> (field-write nx :content 1000 [:a :b :c]) {:a {:b {:c {:content 1000 user=> (macroexpand '(field-write nx :content 1000 [:a :b :c])) (clojure/assoc nx :a (clojure/assoc (clojure/-> nx :a) :b (clojure/assoc (clojure/-> nx :a :b) :c (clojure/assoc (clojure/-> nx :a :b :c):content 1000 [formatting added above for readability] It seems to be working fine but I thought it may be good to get inputs from the Clojure experts here to see if there is a better way to do this in Clojure. (def nx {:a {:b {:c {:content 10) (def field-write) (defmacro field-write [st k v access-spec] ; st=data, k=key to update, v=val to put, access-spec=access vector (if (pred/empty? access-spec) `(assoc ~st ~k ~v) (field-write st (last access-spec) `(assoc (-> ~st [EMAIL PROTECTED]) ~k ~v) (butlast access-spec Thanks. Parth --~--~-~--~~~---~--~~ 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 To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~--~~~~--~~--~--~---