Re: generator in Clojure

2010-10-14 Thread Konrad Hinsen

On 14 Oct 2010, at 21:52, clwham...@gmail.com wrote:


I need a function that produces the 'next' value from a lazy-seq --
something like a Python generator. I imagine it would have to be some
sort of closure like:

(def next-sine
   (let [sines (atom (cycle (map sin (range 0 6.28 0.01]
   #(swap! sines rest)))

Is there a more idomatic way of doing this? I don't see a lot of use
of closures in clojure...


Closures are common in Clojure, but mostly they capture values rather  
than storage locations.


Could you tell us why you "need" a function that relies on mutable  
state? Clojure has lots of functions to make, transform, and use  
sequences in a functional style, and those are usually preferred.


If your need comes from the wish to do stream processing without  
passing the stream around explicitly among lots of functions, consider  
using monads to abstract away the stream argument:



http://github.com/clojure/clojure-contrib/blob/master/modules/stream-utils/src/main/clojure/clojure/contrib/stream_utils.clj

Konrad.

--
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: Java Source Indentation

2010-10-14 Thread B Smith-Mannschott
On Fri, Oct 15, 2010 at 04:13, David Jacobs
 wrote:
> I've just started learning Clojure and I'm excited about what I see. The 
> combination of power and sophistication in the language is refreshing, and 
> I've started to dive into the source code to understand it better.
>
> One meta-observation has come out of my scouring.
>
> The indentation used for the part of Clojure that's written in Clojure is 
> beautifully indented, well documented, and generally easy to work through. On 
> the other hand, the Java source doesn't look so consistent, either internally 
> or with standard practices--especially as regards whitespace, indentation, 
> and braces.
>
> It may seem like a small thing, but I think that having well-formatted, 
> consistent source code is important.
>
> Would there be any objection to reformatting the Java source to make it 
> consistent? I wouldn't mind undertaking that project in my free time.
>
> Thoughts?
>
> David

Yea, it's an oddball:

Method headers tend to be in sun style, with the opening brace at the
end of the line. control structures (method bodies) tend to be in
whitesmith style [1]. Indentation is mostly with hard tabs. Since
there are some spaces mixed in there occasionally, things can look a
little drunken when you don't have tab size set to that of the author.
Oh, and methods and nested classes of the top-level class are
outdented to column zero. So, in total, it looks pretty unsettling at
first if you're used to more conventional formatting.

[1] http://en.wikipedia.org/wiki/Indent_style#Whitesmiths_style

But, one can get used to almost anything. It doesn't bother me much
anymore. If that's how Rich likes it, who am I to argue?

// Ben

-- 
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: Java Source Indentation

2010-10-14 Thread Santosh Rajan
IMHO if it is not broken, dont fix it. I am sure the original authors are
aware and are very much around. Probably they would be the best people to do
it anyway.

On Fri, Oct 15, 2010 at 7:43 AM, David Jacobs <
develo...@allthingsprogress.com> wrote:

> I've just started learning Clojure and I'm excited about what I see. The
> combination of power and sophistication in the language is refreshing, and
> I've started to dive into the source code to understand it better.
>
> One meta-observation has come out of my scouring.
>
> The indentation used for the part of Clojure that's written in Clojure is
> beautifully indented, well documented, and generally easy to work through.
> On the other hand, the Java source doesn't look so consistent, either
> internally or with standard practices--especially as regards whitespace,
> indentation, and braces.
>
> It may seem like a small thing, but I think that having well-formatted,
> consistent source code is important.
>
> Would there be any objection to reformatting the Java source to make it
> consistent? I wouldn't mind undertaking that project in my free time.
>
> Thoughts?
>
> David
>
> --
> 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




-- 
http://hi.im/santosh

-- 
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

Java Source Indentation

2010-10-14 Thread David Jacobs
I've just started learning Clojure and I'm excited about what I see. The 
combination of power and sophistication in the language is refreshing, and I've 
started to dive into the source code to understand it better.

One meta-observation has come out of my scouring.

The indentation used for the part of Clojure that's written in Clojure is 
beautifully indented, well documented, and generally easy to work through. On 
the other hand, the Java source doesn't look so consistent, either internally 
or with standard practices--especially as regards whitespace, indentation, and 
braces.

It may seem like a small thing, but I think that having well-formatted, 
consistent source code is important.

Would there be any objection to reformatting the Java source to make it 
consistent? I wouldn't mind undertaking that project in my free time.

Thoughts?

David

-- 
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: sql utilities

2010-10-14 Thread Stuart Campbell
Thanks Kyle. Looks useful!

On 15 October 2010 09:25, Saul Hazledine  wrote:

> On Oct 14, 9:16 pm, "Kyle R. Burton"  wrote:
> > I've written some sql helper functions that will do things like list
> > the objects in the database and describe a table.  I've found these
> > handy when doing interactive development as I don't have to jump over
> > to another app to see what the make up of tables are.  I've also used
> > it in some scenarios when generating code from the database schema.
> >
>
> Very cool. If you have no joy getting it into contrib you can have
> write access to clj-sql if you want it:
>
> http://github.com/alienscience/clj-sql
>
> Otherwise, as Shanatu says, a github project of your own would be
> welcome and is sure to be used by others.
>
> Saul
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clojure@googlegroups.com
> Note that posts from new members are moderated - please be patient with
> your first post.
> To unsubscribe from this group, send email to
> clojure+unsubscr...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
>

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To 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: CongoMongo - which version/fork is most uptodate

2010-10-14 Thread Mark Engelberg
I've been having trouble with congomongo for the reasons you
specified, and a few more (doesn't sort, ran into a bug where limit
was working properly with large datasets).

I recently switched to the "karras" clojure wrapper for mongodb
(http://github.com/wilkes/karras), and found it to be much more
fully-featured and reliable, and it works with the 2.2 mongo java
driver and has no reflection warnings.

Congomongo has a somewhat simper, more intuitive api, and the karras
documentation is mostly non-existent (I figured it out primarily by
reading the source files "collection" and "sugar"), but overall, I'm
very glad I switched.

I agree that mongodb fits well with Clojure and I intend to use it
whenever possible.  My only real negative issue with mongodb is that
it has severe size constraints on a 32-bit platform.  Sadly, for my
current project, I hit a wall with mongo.  After trying out couchDB,
sqlite, h2, and a couple other options, I eventually settled on MySQL
as the one that worked best to manipulate the quantity of data I need
into the file and memory limitations of my machine.  None of the
options were anywhere near as fast or as easy to program as mongo,
though.  Almost makes me wish I were running a 64-bit OS.

The only other Clojure/mongo "gotcha" I've experienced is that if you
use Clojure's lazy sequences to stream through query results, and you
do some sort of update on the objects in the query, it screws with the
streaming query and the lazy stream can end up skipping over objects
that fit the query.  So it's vital to use doall to force the entire
lazy stream to be realized before you do any updates.  This is
unfortunate, because it means you're memory bound if you want to
update all the items in your database.

-- 
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: Python like hash-map constructor (a.k.a. dict)

2010-10-14 Thread Alan
I wouldn't say it has *nothing* to do with dotimes. If dotimes were
lazy rather than eager, then his form would do nothing despite the
eagerness of into, because into is not being called:

(for [i (range 100)]
  (into [] (some-expensive-calc)))

On Oct 14, 3:34 pm, Meikel Brandmeyer  wrote:
> Hi,
>
> Am 14.10.2010 um 23:07 schrieb Henk:
>
> > Does dotimes force evaluation?,
>
> At a different level. (dotimes [n 1] (for ...)) does evaluate the for 
> form. But it returns a seq which is never realised. So you do effectively … 
> nothing. (dotimes [n 1] (into [] (for ...))) as in your example does 
> consume the sequence and hence realises it. So all the work defined in the 
> for form is actually done. However this is do to into being eager and has 
> nothing to do with dotimes.
>
> Sincerely
> Meikel

-- 
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: generator in Clojure

2010-10-14 Thread Alan
Yes, it would be. But it's "wildly unlikely" that you need to do it.
You don't say what you're using next-sine! for, but I'll imagine
you're doing something like printing it. Maybe your code looks like:

(dotimes [n num-iters]
  (let [s current-sine]
(next-sine!)
(println s)))

This can easily be done without mutation:

(defn sines []
   (cycle (map #(Math/sin %) (range 0 6.28 0.01

(doseq [s (take num-iters (sines))]
  (println s))

This avoids mutating anything, and is as lazy as you need, because
doseq won't hold onto the head of the (sines) call, and (sines) is in
fact not bound anywhere globally (unlike your sines constant).

If you need to start in the middle of the seq for some reason, you can
(take num-iters (drop n-drop (sines))).

On Oct 14, 1:59 pm, "clwham...@gmail.com"  wrote:
> I originally thought of calling nth on the seq but isn't that pretty
> wildly inefficient?
>
> On Oct 14, 1:38 pm, Moritz Ulrich 
> wrote:
>
> > Are you sure you need to capture the state in next-sine? It's not very
> > clojure-ly to have functions with state. I would capture the state in
> > the caller as an integer and just use get or nth on the lazy seq.
> > If you want to stick to your impure function, please mark it with a !
> > at the end: next-sine!
>
> > On Thu, Oct 14, 2010 at 9:52 PM, clwham...@gmail.com
>
> >  wrote:
> > > I need a function that produces the 'next' value from a lazy-seq --
> > > something like a Python generator. I imagine it would have to be some
> > > sort of closure like:
>
> > > (def next-sine
> > >    (let [sines (atom (cycle (map sin (range 0 6.28 0.01]
> > >        #(swap! sines rest)))
>
> > > Is there a more idomatic way of doing this? I don't see a lot of use
> > > of closures in clojure...
>
> > > --
> > > 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
>
> > --
> > Moritz Ulrich
> > Programmer, Student, Almost normal Guy
>
> >http://www.google.com/profiles/ulrich.moritz
> > BB5F086F-C798-41D5-B742-494C1E9677E8
>
>

-- 
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: Python like hash-map constructor (a.k.a. dict)

2010-10-14 Thread Meikel Brandmeyer
Hi,

Am 14.10.2010 um 23:07 schrieb Henk:

> Does dotimes force evaluation?,

At a different level. (dotimes [n 1] (for ...)) does evaluate the for form. 
But it returns a seq which is never realised. So you do effectively … nothing. 
(dotimes [n 1] (into [] (for ...))) as in your example does consume the 
sequence and hence realises it. So all the work defined in the for form is 
actually done. However this is do to into being eager and has nothing to do 
with dotimes.

Sincerely
Meikel


-- 
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: sql utilities

2010-10-14 Thread Saul Hazledine
On Oct 14, 9:16 pm, "Kyle R. Burton"  wrote:
> I've written some sql helper functions that will do things like list
> the objects in the database and describe a table.  I've found these
> handy when doing interactive development as I don't have to jump over
> to another app to see what the make up of tables are.  I've also used
> it in some scenarios when generating code from the database schema.
>

Very cool. If you have no joy getting it into contrib you can have
write access to clj-sql if you want it:

http://github.com/alienscience/clj-sql

Otherwise, as Shanatu says, a github project of your own would be
welcome and is sure to be used by others.

Saul

-- 
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


CongoMongo - which version/fork is most uptodate

2010-10-14 Thread gammelgedden
I have recently looked at mongodb and liked the idea of a schema less
database. I found somnium.congomongo and played with that for a while,
but ran into some issues

- it doesnt work with the current release 2.2 of mongo java driver
- lots of reflection warnings
- perhaps lacking some finish...

A quick search revealed that there are a substantial number of forks
around on the net. So, which version is best, most up-to-date, best
tested?

somnium itself? weavejester's? zef hemel? .. there are even more forks
around

I think mongodb looks like a good fit to the dynamc nature of clojure.
Any experiences you want to share?

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
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: Python like hash-map constructor (a.k.a. dict)

2010-10-14 Thread David Nolen
On Thu, Oct 14, 2010 at 4:54 PM, Henk  wrote:

> Thanx!,
>
> That is exactly what I was looking for!,
>
> Being a clojure newbie and a non-native speaker it is hard to find
> the correct function among many in clojure core API :-)
> If only the documentation would provide simple examples like you
> provided...


Growing list of examples here, http://clojuredocs.org. Also the IRC
channel's a great to pick up knowledge.

David

-- 
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: precise numbers

2010-10-14 Thread David Sletten

On Oct 14, 2010, at 12:07 PM, cej38 wrote:

> I am kinda sorry that I started this whole thing.  I don't need
> another lesson in limits.  The simple fact of the matter is that, in
> my code, I run into a place where I have a comparison (= some-value
> (some-function some-data)), the function, data, and value can change.
> In a use case that I am interested in, I run into the problem stated,
> 
> user=> (= 0.0001 (- 12.305 12.3049))
> false
> 
> I am OK with replacing the = function with something like float=
> discussed above, but whatever I change it two needs to work.  If
> anyone has found a way, that reliably works, please post it here.
> Further, <, >, <=, and >= would also be appreciated.  Thank you.
> 
> 

If you define 2 of them, then you get the rest for free. We already have float=:
(defn float=
  ([x y] (float= x y 0.1))
  ([x y epsilon]
 (let [scale (if (or (zero? x) (zero? y)) 1 (Math/abs x))]
   (<= (Math/abs (- x y)) (* scale epsilon )

If x < y, then in our case x should be more than epsilon below y:
(defn float<
  ([x y] (float< x y 0.1))
  ([x y epsilon]
 (let [scale (if (or (zero? x) (zero? y)) 1 (Math/abs x))]
   (< x (- y (* scale epsilon ))

(defn float<=
  ([x y] (or (float< x y) (float= x y)))
  ([x y epsilon] (or (float< x y epsilon) (float= x y epsilon

(defn float>
  ([x y] (not (float<= x y)))
  ([x y epsilon] (not (float<= x y epsilon

(defn float>=
  ([x y] (or (float> x y) (float= x y)))
  ([x y epsilon] (or (float> x y epsilon) (float= x y epsilon

Then you determine how strict epsilon needs to be:
(float< 12.3049 12.305) => false
(float< 12.3049 12.305 1e-6) => true
(float<= 12.305 12.3049) => true
(float<= 12.305 12.3049 1e-6) => false
(float> 12.305 12.3049 1e-6) => true



Have all good days,
David Sletten




-- 
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: Python like hash-map constructor (a.k.a. dict)

2010-10-14 Thread Henk
Does dotimes force evaluation?,
if so, then the Clojure version is about twice as fast for me...
which would be nice to finally find a good dynamic programming
language that is also
nice and fast :-)


the code I tested is this:

(def HHQ [{:id 1956, :firstname "Piet", :lastname
"Puk", :programming_skills #{:java, :php, :closure}}
  {:id 2000, :firstname "Blaat", :lastname
"Aap", :programming_skills #{:java, :php, :python}}
  {:id 2020, :firstname "Jaap", :lastname
"Klaas", :programming_skills #{:cobol, :php, :skala}}])

(time
  (dotimes [n 100]
(into {} (for [x HHQ :when ((x :programming_skills) :java)]
[(x :id) (str (x :firstname) " "  (x :lastname))]

vs the python version

HHQ = [{'id': 1956, 'firstname': "Piet", 'lastname': "Puk",
'programming_skills': set(['java', 'php', 'closure'])},
   {'id': 2000, 'firstname': "Blaat", 'lastname': "Aap",
'programming_skills': set(['java', 'php', 'python'])},
   {'id': 2020, 'firstname': "Jaap", 'lastname': "Klaas",
'programming_skills': set(['cobol', 'php', 'skala'])}]

import time
start = time.time()
for i in range(100):
dict([(x['id'], (x['firstname'] + " " + x['lastname'])) for x in HHQ
if 'java' in x['programming_skills']])
end = time.time()

print end - start

On 14 okt, 19:09, Chris Perkins  wrote:
> On Oct 14, 11:54 am, Henk  wrote:
>
> > (I did some small benchmarks on this), while the list comprehension
> > itself is much faster than python...
>
> Not an answer to your question, but: depending on what you mean by
> "much faster", there is a good chance that you measured the clojure
> for expression doing nothing. You should wrap it in a doall or dorun
> to get a proper timing (like a generator in Python).
>
> Eg: for me, the following are almost exactly the same speed (~45ms):
>
> user=> (time (dorun (for [i (range 10)] [i (* i i)])))
> "Elapsed time: 45.965679 msecs"
>
> C:\Users\chris>python -m timeit "[(i,i*i) for i in range(10)]"
> 10 loops, best of 3: 45.5 msec per loop
>
> - 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
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: generator in Clojure

2010-10-14 Thread clwham...@gmail.com
I originally thought of calling nth on the seq but isn't that pretty
wildly inefficient?

On Oct 14, 1:38 pm, Moritz Ulrich 
wrote:
> Are you sure you need to capture the state in next-sine? It's not very
> clojure-ly to have functions with state. I would capture the state in
> the caller as an integer and just use get or nth on the lazy seq.
> If you want to stick to your impure function, please mark it with a !
> at the end: next-sine!
>
> On Thu, Oct 14, 2010 at 9:52 PM, clwham...@gmail.com
>
>
>
>
>
>
>
>
>
>  wrote:
> > I need a function that produces the 'next' value from a lazy-seq --
> > something like a Python generator. I imagine it would have to be some
> > sort of closure like:
>
> > (def next-sine
> >    (let [sines (atom (cycle (map sin (range 0 6.28 0.01]
> >        #(swap! sines rest)))
>
> > Is there a more idomatic way of doing this? I don't see a lot of use
> > of closures in clojure...
>
> > --
> > 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
>
> --
> Moritz Ulrich
> Programmer, Student, Almost normal Guy
>
> http://www.google.com/profiles/ulrich.moritz
> BB5F086F-C798-41D5-B742-494C1E9677E8

-- 
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: Python like hash-map constructor (a.k.a. dict)

2010-10-14 Thread Henk
Thanx!,

That is exactly what I was looking for!,

Being a clojure newbie and a non-native speaker it is hard to find
the correct function among many in clojure core API :-)
If only the documentation would provide simple examples like you
provided...

On 14 okt, 18:20, liebke  wrote:
> Here's one approach:
>
> (into {} [[:a 1] [:b 2] [:c 3]])
>
> => {:a 1, :b 2, :c 3}
>
> On Oct 14, 11:54 am, Henk  wrote:
>
>
>
> > Hi All,
>
> > In Python I was used to be able to easily create dictionaries from
> > lists of key value 'pairs' (tuples or list), e.g. like this:
>
> > dict([(10, 20), (30, 40)]) #using the dict constructor
> > =>
> > {10:20, 30:40}
>
> > What would be the equivalent in Clojure?, e.g. the normal Clojure hash-
> > map function takes a list
> > of alternating keys and values which is not quite the same.
> > This is a quite common need (especially in the context of initializing
> > a hash-map from a list comprehension, like this:
>
> > (dict (for [x programmers :when ((x :-p rogramming_skills) :java)]
> > [(x :id) (str (x :firstname) " " (x :lastname))]))
>
> > This function seems to do the trick:
>
> > (defn dict [x] (apply hash-map (apply concat x)))
>
> > but it is quite slow, e.g. much slower than the python native version
> > (I did some small benchmarks on this), while the list comprehension
> > itself is much faster than python...

-- 
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: generator in Clojure

2010-10-14 Thread Nicolas Oury
(defn iterate [s]
(let [a (atom s)]
(fn []
   (let [s @a]
  (reset! a (next s))
  (first s))

but it's not very idiomatic in clojure.
(In Lisp it is traditional to hide a state in a closure. A lot of toy
object language work like that)



On Thu, Oct 14, 2010 at 9:38 PM, Moritz Ulrich
 wrote:
> Are you sure you need to capture the state in next-sine? It's not very
> clojure-ly to have functions with state. I would capture the state in
> the caller as an integer and just use get or nth on the lazy seq.
> If you want to stick to your impure function, please mark it with a !
> at the end: next-sine!
>
> On Thu, Oct 14, 2010 at 9:52 PM, clwham...@gmail.com
>  wrote:
>> I need a function that produces the 'next' value from a lazy-seq --
>> something like a Python generator. I imagine it would have to be some
>> sort of closure like:
>>
>> (def next-sine
>>    (let [sines (atom (cycle (map sin (range 0 6.28 0.01]
>>        #(swap! sines rest)))
>>
>> Is there a more idomatic way of doing this? I don't see a lot of use
>> of closures in clojure...
>>
>> --
>> 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
>
>
>
> --
> Moritz Ulrich
> Programmer, Student, Almost normal Guy
>
> http://www.google.com/profiles/ulrich.moritz
> BB5F086F-C798-41D5-B742-494C1E9677E8
>
> --
> 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



-- 
Sent from an IBM Model M, 15 August 1989.

-- 
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: sql utilities

2010-10-14 Thread Kyle R. Burton
> This is fantastic! Does it work reliably for most JDBC drivers? Some
> drivers may not implement meta data API very well, and some drivers
> may have their own idiosyncrasies. You can perhaps setup a GitHub
> project and push to Clojars if this doesn't get into contrib any time
> soon.

I have made an attempt to use only standard SQL and standard JDK api's
- I have tested it against MySQL and PostgreSQL successfully.  I don't
have access to other databases.  I'd be happy to put it into a github
project, but thought I'd offer it to the group first.


Regards,

Kyle


-- 
Twitter: @kyleburton
Blog: http://asymmetrical-view.com/
Fun: http://snapclean.me/

-- 
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: generator in Clojure

2010-10-14 Thread Moritz Ulrich
Are you sure you need to capture the state in next-sine? It's not very
clojure-ly to have functions with state. I would capture the state in
the caller as an integer and just use get or nth on the lazy seq.
If you want to stick to your impure function, please mark it with a !
at the end: next-sine!

On Thu, Oct 14, 2010 at 9:52 PM, clwham...@gmail.com
 wrote:
> I need a function that produces the 'next' value from a lazy-seq --
> something like a Python generator. I imagine it would have to be some
> sort of closure like:
>
> (def next-sine
>    (let [sines (atom (cycle (map sin (range 0 6.28 0.01]
>        #(swap! sines rest)))
>
> Is there a more idomatic way of doing this? I don't see a lot of use
> of closures in clojure...
>
> --
> 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



-- 
Moritz Ulrich
Programmer, Student, Almost normal Guy

http://www.google.com/profiles/ulrich.moritz
BB5F086F-C798-41D5-B742-494C1E9677E8

-- 
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: resultset-seq

2010-10-14 Thread Shantanu Kumar
+1 Sounds good.

Regards,
Shantanu

On Oct 14, 11:58 pm, Mark Engelberg  wrote:
> Since no one chimed in with support or reasoning for resultset-seq's
> current lower-casing behavior, can we discuss changing it to
> case-maintaining behavior, or at least make it something you can set
> with an optional flag?
>
> On Sun, Oct 10, 2010 at 8:41 PM, Mark Engelberg
>
>
>
>  wrote:
> > Why does resultset-seq convert column names to all lower case?  This
> > behavior is screwing me up (my column names are intentionally mixed
> > case) and I don't understand the reasoning.
>
> > Thanks,
>
> > 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
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: sql utilities

2010-10-14 Thread Shantanu Kumar
This is fantastic! Does it work reliably for most JDBC drivers? Some
drivers may not implement meta data API very well, and some drivers
may have their own idiosyncrasies. You can perhaps setup a GitHub
project and push to Clojars if this doesn't get into contrib any time
soon.

Regards,
Shantanu

On Oct 15, 12:16 am, "Kyle R. Burton"  wrote:
> I've written some sql helper functions that will do things like list
> the objects in the database and describe a table.  I've found these
> handy when doing interactive development as I don't have to jump over
> to another app to see what the make up of tables are.  I've also used
> it in some scenarios when generating code from the database schema.
>
> The functions are below, they make use only of standard JDK java.sql
> functions and classes.  I'd like to see if there is any interest in
> adding these to one of the contrib libraries - I'd be happy to clean
> them up, create a patch or send a pull request (I've already submitted
> a contributor agreement).
>
> Best Regards,
>
> Kyle Burton
>
> (defn schemas
>  "Returns a list of the schema names in the database."
>  [db]
>  (sql/with-connection db
>    (let [schemas (.getSchemas (.getMetaData (sql/connection)))]
>      (loop [has-next (.next schemas)
>             res []]
>        (if has-next
>          (let [schema  (.getString schemas 1)]
>            (recur (.next schemas)
>                   (conj res schema)))
>          res)
>
> (defn schema-objects
>  "Returns a list of maps describing the objects in the database.  The
>  maps include: :catalog, :schema, :name, :type and :remarks as per
>  the JDBC spec."
>  [db schema]
>  (sql/with-connection db
>    (let [db-meta (.getMetaData (sql/connection))
>          ;; NB: "public" is the default for postgres
>          tables  (.getTables db-meta nil schema "%" nil)]
>      (loop [has-next (.next tables)
>             res []]
>        (if has-next
>          (let [table {:catalog  (.getString tables  1)
>                       :schema   (.getString tables  2)
>                       :name     (.getString tables  3)
>                       :type     (.getString tables  4)
>                       :remakrs  (.getString tables  5)}]
>            (recur (.next tables)
>                   (conj res table)))
>          res)
>
> (defn schema-tables [db schema]
>  (filter #(= (:type %1) "TABLE") (schema-objects db schema)))
>
> (defn- range-sql [end]
>    (range 1 (+ 1 end)))
>
> (defn describe-table
>  "Returns a list of column descriptions (maps) for the table.  The
>   maps
>   contain: :name, :catalog, :display-zie, :type, :precision, :scale
>   :is-auto-increment, :is-case-sensitive, :is-currency
>   :is-definitely-writable, :is-nullable, :is-read-only
>   :is-searchable, :is-signed, :is-writable."
>  [db table-name]
>  (sql/with-connection db
>    (let [ps (.prepareStatement (sql/connection) (format "SELECT * FROM
> %s WHERE 0 = 1" table-name))
>          rs (.executeQuery ps)
>          rs-meta (.getMetaData rs)]
>      (loop [[idx & idxs] (range-sql (.getColumnCount rs-meta))
>             res []]
>        (if idx
>          (recur idxs (conj res {:name
> (.getColumnName rs-meta idx)
>                                 :catalog
> (.getCatalogName rs-meta idx)
>                                 :display-size
> (.getColumnDisplaySize rs-meta idx)
>                                 :type
> (.getColumnType rs-meta idx)
>                                 :precision              (.getPrecision
> rs-meta idx)
>                                 :scale                  (.getScale rs-meta 
> idx)
>                                 :is-auto-increment
> (.isAutoIncrement rs-meta idx)
>                                 :is-case-sensitive
> (.isCaseSensitive rs-meta idx)
>                                 :is-currency            (.isCurrency
> rs-meta idx)
>                                 :is-definitely-writable
> (.isDefinitelyWritable rs-meta idx)
>                                 :is-nullable            (.isNullable
> rs-meta idx)
>                                 :is-read-only           (.isReadOnly
> rs-meta idx)
>                                 :is-searchable          (.isSearchable
> rs-meta idx)
>                                 :is-signed              (.isSigned rs-meta 
> idx)
>                                 :is-writable            (.isWritable
> rs-meta idx)}))
>          res)
>
> --
> Twitter: @kyleburton
> Blog:http://asymmetrical-view.com/
> Fun:http://snapclean.me/

-- 
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: Test-driven development in Clojure

2010-10-14 Thread Armando Blancas
Maybe something like this. Those calls polymorphic on the returrn
value of the anynimous function, so this is more powerful than
overloading.

(defmulti load-page (fn [p n] (:id p)))
(defmethod load-page :db [loader name] (println "db provider for page"
name))
(defmethod load-page :fs [loader name] (println "fs provider for page"
name))
(defmethod load-page :mock [loader name] (println "mock provider for
page" name))

The loader data structure has a field that identifies which provider
it has. The loader and providers may be records or maps:
(defrecord prov-rec [f1 f2 f3])
(defrecord loader-rec [id prov])

;; tests
(def loader (loader-rec. :mock (prov-rec. nil nil nil)))
(load-page loader "index.html")
;; real work
(def loader (loader-rec. :db (prov-rec. "data" "user" "pwd")))
(load-page loader "index.html")

Works with this one, too:
(def loader { :id :fs :prov { :user "root" :pwd "***"} } )


On Oct 14, 3:08 am, "Felix H. Dahlke"  wrote:
> Oh, I think I missed your suggestion of multimethods. They do in fact
> look pretty interesting, but I wasn't able to figure out how that would
> solve my problem - they look more like overloading than polymorphism to
> me. Would you mind posting a variant of my example that uses multimethods?
>
> On 14/10/10 04:28, Armando Blancas wrote:
>
>
>
> > One thing that OOP and FP can have in common is the use of
> > polymorphism. With protocols and types you can implement your Java
> > design efficiently because you'll get basically the same interfaces
> > and classes. The thing about hiding the calls to instances of a data
> > type is only to make the client code not reply on the interop
> > notation, even if it is only to call a method on them, just like
> > Clojure core functions do.
>
> > With multimethods you can have different versions of the same
> > function. You're right, you call it with the necessary data, one of
> > which will be the one that controls the dispatch. Both data types and
> > multimethods provide late-binding; the difference is that multi-
> > methods are objects turned inside-out, as if you keep a reference to
> > this (as a record with fields) and use in function calls. And each
> > method is a particular responsibility. That's how I think about it,
> > anyway.
>
> > Either choice should be fine. I write Java interfaces for
> > implementations in Clojure when I want interop with Java, otherwise I
> > use multimethods and do it all in Clojure.
>
> > On Oct 13, 1:37 pm, "Felix H. Dahlke"  wrote:
> >> I see. So instead of using interfaces and implementations of these, I
> >> would simply use closures, one for mock and one for production? That was
> >> actually my first attempt, but I didn't like it back then.
>
> >> Take this code for example - passing a function just to have it called
> >> feels weird:
>
> >> (defn load-page [provider name]
> >>   (provider name))
>
> >> (load-page (make-mock-provider) "home")
>
> >> In Java, this would probably look like this:
>
> >> class PageLoader {
> >>     Provider provider;
>
> >>     PageLoader(Provider p) {
> >>         provider = p;
> >>     }
>
> >>     Page loadPage(String name) {
> >>         provider.loadPage(name);
> >>     }
>
> >> }
>
> >> PageLoader l = new PageLoader(new MockProvider());
> >> l.loadPage("home");
>
> >> Then again, it might just feel weird because I've gotten very used to
> >> OOP. In my Java code, loading pages is a responsibility of the
> >> PageLoader and it delegates it to the Provider. Objects have
> >> responsibilities and send messages to each other to fulfill these,
> >> that's OOP.
>
> >> In functional programming, there's simply a function that has a certain
> >> functionality, and everything it needs to fulfill it has to be provided
> >> by the caller. That's at least how I understand it by now.
>
> >> Maybe I should just call the function returned by (make-mock-provider)
> >> directly? The interface in Java has the great benefit of ensuring type
> >> safety (plus there's no closures yet, so it's the only way), but does
> >> this make sense in a dynamic language? I mean, if I passed an
> >> implementation of the wrong interface or a closure with the wrong number
> >> of arguments, wouldn't both situations result in weird runtime errors?
>
> >> On 12/10/10 22:34, Armando Blancas wrote:
>
>  Back to my question: Am I trying to do Java in Clojure? Is there a more
>  Lisp-y way to do this?
>
> >>> You can hide the types so your client code is more lispy:
> >>> (defn load-page [prov] (.loadPage prov))
> >>> ;;test
> >>> (def mp (make-mock-provider)) ... (load-page mp)
> >>> ;;production
> >>> (def prov (make-provider)) ... (load-page prov)
>
> >>> Depending on your app the provider could be a singleton and need not
> >>> be passed to each function. Another option is multimethods, in which
> >>> case you'd be using mock functions with an argument that would
> >>> indicate which version to dispatch to.
>
> >>> As for the repl, I think it works just as well for bottom-up 

generator in Clojure

2010-10-14 Thread clwham...@gmail.com
I need a function that produces the 'next' value from a lazy-seq --
something like a Python generator. I imagine it would have to be some
sort of closure like:

(def next-sine
(let [sines (atom (cycle (map sin (range 0 6.28 0.01]
#(swap! sines rest)))

Is there a more idomatic way of doing this? I don't see a lot of use
of closures in clojure...

-- 
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: RFE: modify description of "assoc"

2010-10-14 Thread Michael Ossareh
On Thu, Oct 14, 2010 at 08:02, Ralph  wrote:

> First, how do I submit a request for enhancement?
>
>
I believe the process is:

a) register on assembla,
b) submit ticket (
http://www.assembla.com/spaces/clojure/tickets/custom_report/2729 )

If you intend to provide the change via a pull request on github you need to
provide the contributor agreement (CA) paperwork

http://clojure.org/contributing



> Second, the documentation for "assoc" in clojure.core should probably
> include "(assoc vector index val)" and "(assoc vector index val &
> ivs)" in the usage line.
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clojure@googlegroups.com
> Note that posts from new members are moderated - please be patient with
> your first post.
> To unsubscribe from this group, send email to
> clojure+unsubscr...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To 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

sql utilities

2010-10-14 Thread Kyle R. Burton
I've written some sql helper functions that will do things like list
the objects in the database and describe a table.  I've found these
handy when doing interactive development as I don't have to jump over
to another app to see what the make up of tables are.  I've also used
it in some scenarios when generating code from the database schema.

The functions are below, they make use only of standard JDK java.sql
functions and classes.  I'd like to see if there is any interest in
adding these to one of the contrib libraries - I'd be happy to clean
them up, create a patch or send a pull request (I've already submitted
a contributor agreement).

Best Regards,

Kyle Burton


(defn schemas
 "Returns a list of the schema names in the database."
 [db]
 (sql/with-connection db
   (let [schemas (.getSchemas (.getMetaData (sql/connection)))]
     (loop [has-next (.next schemas)
            res []]
       (if has-next
         (let [schema  (.getString schemas 1)]
           (recur (.next schemas)
                  (conj res schema)))
         res)

(defn schema-objects
 "Returns a list of maps describing the objects in the database.  The
 maps include: :catalog, :schema, :name, :type and :remarks as per
 the JDBC spec."
 [db schema]
 (sql/with-connection db
   (let [db-meta (.getMetaData (sql/connection))
         ;; NB: "public" is the default for postgres
         tables  (.getTables db-meta nil schema "%" nil)]
     (loop [has-next (.next tables)
            res []]
       (if has-next
         (let [table {:catalog  (.getString tables  1)
                      :schema   (.getString tables  2)
                      :name     (.getString tables  3)
                      :type     (.getString tables  4)
                      :remakrs  (.getString tables  5)}]
           (recur (.next tables)
                  (conj res table)))
         res)

(defn schema-tables [db schema]
 (filter #(= (:type %1) "TABLE") (schema-objects db schema)))

(defn- range-sql [end]
   (range 1 (+ 1 end)))

(defn describe-table
 "Returns a list of column descriptions (maps) for the table.  The
  maps
  contain: :name, :catalog, :display-zie, :type, :precision, :scale
  :is-auto-increment, :is-case-sensitive, :is-currency
  :is-definitely-writable, :is-nullable, :is-read-only
  :is-searchable, :is-signed, :is-writable."
 [db table-name]
 (sql/with-connection db
   (let [ps (.prepareStatement (sql/connection) (format "SELECT * FROM
%s WHERE 0 = 1" table-name))
         rs (.executeQuery ps)
         rs-meta (.getMetaData rs)]
     (loop [[idx & idxs] (range-sql (.getColumnCount rs-meta))
            res []]
       (if idx
         (recur idxs (conj res {:name
(.getColumnName rs-meta idx)
                                :catalog
(.getCatalogName rs-meta idx)
                                :display-size
(.getColumnDisplaySize rs-meta idx)
                                :type
(.getColumnType rs-meta idx)
                                :precision              (.getPrecision
rs-meta idx)
                                :scale                  (.getScale rs-meta idx)
                                :is-auto-increment
(.isAutoIncrement rs-meta idx)
                                :is-case-sensitive
(.isCaseSensitive rs-meta idx)
                                :is-currency            (.isCurrency
rs-meta idx)
                                :is-definitely-writable
(.isDefinitelyWritable rs-meta idx)
                                :is-nullable            (.isNullable
rs-meta idx)
                                :is-read-only           (.isReadOnly
rs-meta idx)
                                :is-searchable          (.isSearchable
rs-meta idx)
                                :is-signed              (.isSigned rs-meta idx)
                                :is-writable            (.isWritable
rs-meta idx)}))
         res)



-- 
Twitter: @kyleburton
Blog: http://asymmetrical-view.com/
Fun: http://snapclean.me/

-- 
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: resultset-seq

2010-10-14 Thread Mark Engelberg
Since no one chimed in with support or reasoning for resultset-seq's
current lower-casing behavior, can we discuss changing it to
case-maintaining behavior, or at least make it something you can set
with an optional flag?

On Sun, Oct 10, 2010 at 8:41 PM, Mark Engelberg
 wrote:
> Why does resultset-seq convert column names to all lower case?  This
> behavior is screwing me up (my column names are intentionally mixed
> case) and I don't understand the reasoning.
>
> Thanks,
>
> 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
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: Python like hash-map constructor (a.k.a. dict)

2010-10-14 Thread Chris Perkins
On Oct 14, 11:54 am, Henk  wrote:
> (I did some small benchmarks on this), while the list comprehension
> itself is much faster than python...

Not an answer to your question, but: depending on what you mean by
"much faster", there is a good chance that you measured the clojure
for expression doing nothing. You should wrap it in a doall or dorun
to get a proper timing (like a generator in Python).

Eg: for me, the following are almost exactly the same speed (~45ms):

user=> (time (dorun (for [i (range 10)] [i (* i i)])))
"Elapsed time: 45.965679 msecs"

C:\Users\chris>python -m timeit "[(i,i*i) for i in range(10)]"
10 loops, best of 3: 45.5 msec per loop


- 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
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: precise numbers

2010-10-14 Thread Brian Hurt
On Thu, Oct 14, 2010 at 12:07 PM, cej38  wrote:

> I am kinda sorry that I started this whole thing.  I don't need
> another lesson in limits.  The simple fact of the matter is that, in
> my code, I run into a place where I have a comparison (= some-value
> (some-function some-data)), the function, data, and value can change.
> In a use case that I am interested in, I run into the problem stated,
>
> user=> (= 0.0001 (- 12.305 12.3049))
> false
>
> I am OK with replacing the = function with something like float=
> discussed above, but whatever I change it two needs to work.  If
> anyone has found a way, that reliably works, please post it here.
> Further, <, >, <=, and >= would also be appreciated.  Thank you.
>
>
>
Comparing two floats for equality is almost always wrong.  What you want to
do is check whether their difference is less than some small number.  To
compare two floating point numbers x and y, you want to do (<= (Math/abs (-
x y)) epsilon), where epsilon is some suitably small number (based on the
size of the error of the computation).

Brian


>
>
>
>
> On Oct 13, 6:56 pm, David Sletten  wrote:
> > Here's a slightly more informal argument. Suppose you challenge me that 1
> is not equal to 0.... What you are saying is that 1 - 0.... is not
> equal to 0, i.e., the difference is more than 0. But for any positive value
> arbitrarily close to 0 I can show that 0.999... is closer to 1 than that. If
> you were to say that the difference is 0.1, I could show that 0.999... > 0.9
> so the difference is smaller. For every 0 you added to your challenge: 0.1,
> 0.01, 0.001 I could provide a counterexample with another 9: 0.9, 0.99,
> 0.999, ... In other words, there is no positive number that satisfies your
> claim, so equality must hold.
> >
> > Have all good days,
> > David Sletten
> >
> > On Oct 13, 2010, at 6:36 PM, Matt Fowles wrote:
> >
> >
> >
> > > Felix~
> >
> > > You are correct that the sequence of numbers
> >
> > > 0.9
> > > 0.99
> > > 0.999
> > > ...
> >
> > > asymptotically approaches 1; however, the number 0.... (with an
> infinite number of 9s) is equal to 1.  The formal proof of this is fairly
> tricky as the definition of the real number is usually done as an
> equivalence class of Cauchy sequences; a simplified version of the proof can
> be thought of as follows:
> >
> > > For any two real numbers a and b there exists an infinite number of
> real numbers c such that a < c < b.  However, there do not exist any numbers
> between 0.9... and 1, thus they must be same number.
> >
> > > As it turns out, it took mathematicians a long time to nail down
> formally exactly what we naively think of as "numbers".
> >
> > > Matt
> >
> > > On Wed, Oct 13, 2010 at 6:27 PM, Felix H. Dahlke 
> wrote:
> > > On 13/10/10 22:28, David Sletten wrote:
> >
> > > > On Oct 12, 2010, at 5:44 PM, Brian Hurt wrote:
> >
> > > >>   For example, in base 10, 1/3 * 3 = 0.9...
> >
> > > > It may seem counterintuitive, but that statement is perfectly true.
> > > > 1 = 0....
> >
> > > > That's a good test of how well you understand infinity.
> >
> > > I'm clearly not a mathematician, but doesn't 0.9... asymptotically
> > > approach 1, i.e. never reaching it? How is that the same as 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
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clojure@googlegroups.com
> Note that posts from new members are moderated - please be patient with
> your first post.
> To unsubscribe from this group, send email to
> clojure+unsubscr...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
>

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To 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: Python like hash-map constructor (a.k.a. dict)

2010-10-14 Thread liebke
Here's one approach:

(into {} [[:a 1] [:b 2] [:c 3]])

=> {:a 1, :b 2, :c 3}

On Oct 14, 11:54 am, Henk  wrote:
> Hi All,
>
> In Python I was used to be able to easily create dictionaries from
> lists of key value 'pairs' (tuples or list), e.g. like this:
>
> dict([(10, 20), (30, 40)]) #using the dict constructor
> =>
> {10:20, 30:40}
>
> What would be the equivalent in Clojure?, e.g. the normal Clojure hash-
> map function takes a list
> of alternating keys and values which is not quite the same.
> This is a quite common need (especially in the context of initializing
> a hash-map from a list comprehension, like this:
>
> (dict (for [x programmers :when ((x :-p rogramming_skills) :java)]
> [(x :id) (str (x :firstname) " " (x :lastname))]))
>
> This function seems to do the trick:
>
> (defn dict [x] (apply hash-map (apply concat x)))
>
> but it is quite slow, e.g. much slower than the python native version
> (I did some small benchmarks on this), while the list comprehension
> itself is much faster than python...

-- 
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


Python like hash-map constructor (a.k.a. dict)

2010-10-14 Thread Henk
Hi All,

In Python I was used to be able to easily create dictionaries from
lists of key value 'pairs' (tuples or list), e.g. like this:

dict([(10, 20), (30, 40)]) #using the dict constructor
=>
{10:20, 30:40}

What would be the equivalent in Clojure?, e.g. the normal Clojure hash-
map function takes a list
of alternating keys and values which is not quite the same.
This is a quite common need (especially in the context of initializing
a hash-map from a list comprehension, like this:

(dict (for [x programmers :when ((x :-p rogramming_skills) :java)]
[(x :id) (str (x :firstname) " " (x :lastname))]))

This function seems to do the trick:

(defn dict [x] (apply hash-map (apply concat x)))

but it is quite slow, e.g. much slower than the python native version
(I did some small benchmarks on this), while the list comprehension
itself is much faster than python...

-- 
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: precise numbers

2010-10-14 Thread cej38
I am kinda sorry that I started this whole thing.  I don't need
another lesson in limits.  The simple fact of the matter is that, in
my code, I run into a place where I have a comparison (= some-value
(some-function some-data)), the function, data, and value can change.
In a use case that I am interested in, I run into the problem stated,

user=> (= 0.0001 (- 12.305 12.3049))
false

I am OK with replacing the = function with something like float=
discussed above, but whatever I change it two needs to work.  If
anyone has found a way, that reliably works, please post it here.
Further, <, >, <=, and >= would also be appreciated.  Thank you.






On Oct 13, 6:56 pm, David Sletten  wrote:
> Here's a slightly more informal argument. Suppose you challenge me that 1 is 
> not equal to 0.... What you are saying is that 1 - 0.... is not equal 
> to 0, i.e., the difference is more than 0. But for any positive value 
> arbitrarily close to 0 I can show that 0.999... is closer to 1 than that. If 
> you were to say that the difference is 0.1, I could show that 0.999... > 0.9 
> so the difference is smaller. For every 0 you added to your challenge: 0.1, 
> 0.01, 0.001 I could provide a counterexample with another 9: 0.9, 0.99, 
> 0.999, ... In other words, there is no positive number that satisfies your 
> claim, so equality must hold.
>
> Have all good days,
> David Sletten
>
> On Oct 13, 2010, at 6:36 PM, Matt Fowles wrote:
>
>
>
> > Felix~
>
> > You are correct that the sequence of numbers
>
> > 0.9
> > 0.99
> > 0.999
> > ...
>
> > asymptotically approaches 1; however, the number 0.... (with an 
> > infinite number of 9s) is equal to 1.  The formal proof of this is fairly 
> > tricky as the definition of the real number is usually done as an 
> > equivalence class of Cauchy sequences; a simplified version of the proof 
> > can be thought of as follows:
>
> > For any two real numbers a and b there exists an infinite number of real 
> > numbers c such that a < c < b.  However, there do not exist any numbers 
> > between 0.9... and 1, thus they must be same number.
>
> > As it turns out, it took mathematicians a long time to nail down formally 
> > exactly what we naively think of as "numbers".
>
> > Matt
>
> > On Wed, Oct 13, 2010 at 6:27 PM, Felix H. Dahlke  wrote:
> > On 13/10/10 22:28, David Sletten wrote:
>
> > > On Oct 12, 2010, at 5:44 PM, Brian Hurt wrote:
>
> > >>   For example, in base 10, 1/3 * 3 = 0.9...
>
> > > It may seem counterintuitive, but that statement is perfectly true.
> > > 1 = 0....
>
> > > That's a good test of how well you understand infinity.
>
> > I'm clearly not a mathematician, but doesn't 0.9... asymptotically
> > approach 1, i.e. never reaching it? How is that the same as 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

-- 
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: Override print-method of struct

2010-10-14 Thread andrei


> Maybe you could use a parent map.
> You have a normal tree, and then you have a map where
> you can get the parent for a given node. I don't know if this
> will be too slow for your problem - it's just an idea.

I haven't thought about it, thank you. I'm going to try different
options and decide later. One disadvantage of your approach I see is
that you need to store 2 vars: one for the tree root, and another for
parent map. On the other hand, this style may be easier to treat in a
direct functional style then recursive one.

-- 
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


RFE: modify description of "assoc"

2010-10-14 Thread Ralph
First, how do I submit a request for enhancement?

Second, the documentation for "assoc" in clojure.core should probably
include "(assoc vector index val)" and "(assoc vector index val &
ivs)" in the usage line.

-- 
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: Override print-method of struct

2010-10-14 Thread sune.simonsen
Maybe you could use a parent map.
You have a normal tree, and then you have a map where
you can get the parent for a given node. I don't know if this
will be too slow for your problem - it's just an idea.

Kind regards Sune

On Oct 13, 6:45 pm, andrei  wrote:
> How can I override print-method for a map, defined with defstruct?
>
> I have to create object hierarchy: one map is a parent for another,
> i.e. it holds link to a child, and another is a child for the first
> one, i.e. holds link to a parent. When I try to print it, I get
> StackOverflowError since printer tries recursively print objects:
>
>  parent -> child -> parent -> child -> 
>
> The best solution I see is to override print-method or str, so the
> printing will go normally. I found this topic:
>
> http://groups.google.com/group/clojure/browse_thread/thread/4a675222f...
>
> which shows how to override print-method for objects defined by
> deftype, but is there a way to do same trick for maps? Maybe it is
> possible to add some special tag to object's meta? Or to redefine
> print-method in the only namespace?
>
> Or maybe I'm just looking at the wrong direction?

-- 
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: precise numbers

2010-10-14 Thread Julian
For the sake of comparison with other LISPs - some Scheme
implementations have an exact? function for dealing with non-precise
numbers.

This seems not to have come across to Clojure. (Although we do have
ratios and BigInteger).

JG

-- 
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: Test-driven development in Clojure

2010-10-14 Thread Felix H. Dahlke
Oh, I think I missed your suggestion of multimethods. They do in fact
look pretty interesting, but I wasn't able to figure out how that would
solve my problem - they look more like overloading than polymorphism to
me. Would you mind posting a variant of my example that uses multimethods?

On 14/10/10 04:28, Armando Blancas wrote:
> One thing that OOP and FP can have in common is the use of
> polymorphism. With protocols and types you can implement your Java
> design efficiently because you'll get basically the same interfaces
> and classes. The thing about hiding the calls to instances of a data
> type is only to make the client code not reply on the interop
> notation, even if it is only to call a method on them, just like
> Clojure core functions do.
> 
> With multimethods you can have different versions of the same
> function. You're right, you call it with the necessary data, one of
> which will be the one that controls the dispatch. Both data types and
> multimethods provide late-binding; the difference is that multi-
> methods are objects turned inside-out, as if you keep a reference to
> this (as a record with fields) and use in function calls. And each
> method is a particular responsibility. That's how I think about it,
> anyway.
> 
> Either choice should be fine. I write Java interfaces for
> implementations in Clojure when I want interop with Java, otherwise I
> use multimethods and do it all in Clojure.
> 
> On Oct 13, 1:37 pm, "Felix H. Dahlke"  wrote:
>> I see. So instead of using interfaces and implementations of these, I
>> would simply use closures, one for mock and one for production? That was
>> actually my first attempt, but I didn't like it back then.
>>
>> Take this code for example - passing a function just to have it called
>> feels weird:
>>
>> (defn load-page [provider name]
>>   (provider name))
>>
>> (load-page (make-mock-provider) "home")
>>
>> In Java, this would probably look like this:
>>
>> class PageLoader {
>> Provider provider;
>>
>> PageLoader(Provider p) {
>> provider = p;
>> }
>>
>> Page loadPage(String name) {
>> provider.loadPage(name);
>> }
>>
>> }
>>
>> PageLoader l = new PageLoader(new MockProvider());
>> l.loadPage("home");
>>
>> Then again, it might just feel weird because I've gotten very used to
>> OOP. In my Java code, loading pages is a responsibility of the
>> PageLoader and it delegates it to the Provider. Objects have
>> responsibilities and send messages to each other to fulfill these,
>> that's OOP.
>>
>> In functional programming, there's simply a function that has a certain
>> functionality, and everything it needs to fulfill it has to be provided
>> by the caller. That's at least how I understand it by now.
>>
>> Maybe I should just call the function returned by (make-mock-provider)
>> directly? The interface in Java has the great benefit of ensuring type
>> safety (plus there's no closures yet, so it's the only way), but does
>> this make sense in a dynamic language? I mean, if I passed an
>> implementation of the wrong interface or a closure with the wrong number
>> of arguments, wouldn't both situations result in weird runtime errors?
>>
>> On 12/10/10 22:34, Armando Blancas wrote:
>>
 Back to my question: Am I trying to do Java in Clojure? Is there a more
 Lisp-y way to do this?
>>
>>> You can hide the types so your client code is more lispy:
>>> (defn load-page [prov] (.loadPage prov))
>>> ;;test
>>> (def mp (make-mock-provider)) ... (load-page mp)
>>> ;;production
>>> (def prov (make-provider)) ... (load-page prov)
>>
>>> Depending on your app the provider could be a singleton and need not
>>> be passed to each function. Another option is multimethods, in which
>>> case you'd be using mock functions with an argument that would
>>> indicate which version to dispatch to.
>>
>>> As for the repl, I think it works just as well for bottom-up and top-
>>> down development. I use it for both all the time and to avoid throw-
>>> away tests I write them top-down, black-box for only what's visible to
>>> client/interop code first, then move down the layers as the code is
>>> more mature and stable. I'm not really into TDD but I depend on a test
>>> suite as complete as I can get it.
>>
>>
>>
>>  signature.asc
>> < 1KViewDownload
> 




signature.asc
Description: OpenPGP digital signature


Re: Override print-method of struct

2010-10-14 Thread andrei
Interesting approach. I'll keep it in mind, but for this particular
project I actually have to have mutable objects - both parents and
children must be modifyable. Also I really want to see them as
collections: closures where used everywhere in the previous version of
program, and it was very hard to test them in REPL, since you cannot
see actual data, stored in closure. Nevertheless, I agree with you
that some kind of combining collections and closures is the best
approach for pure functional applications.

On Oct 14, 2:33 am, meb  wrote:
> Instead of using a ref, you might consider using a closure, which
> seems a little more functional.
>
> So every child would simply store a function that when called would
> return the map of the parent, map you capture using a closure.  This
> would also reduce your printing problems because functions just print
> their classname, and you would know that the function brings you back
> to the parent.
>
> I did this for a Neo4j wrapper I wrote to idiomatically represent
> traversing webs and trees.
>
> Would that help anyway?  Then you wouldn't have to worry about messing
> with redefining prints or using alters.  The thunk would be created as
> part of the process.
>
> Mark
>
> On Oct 13, 4:21 pm, andrei  wrote:
>
> > That works, thanks!
>
> > Yeah, I understand that it is not the best data structure to use. The
> > task is to create a tree, and it is needed to get all children and all
> > parents of specified node in this tree in a constant time. So, I
> > cannot see another way to do it except storing refs both from parents
> > to children and from children to parents.
>
> > On Oct 14, 12:40 am, Laurent PETIT  wrote:
>
> > > You can add a :type metadata to your maps, and this can be catched by the
> > > (type) method of multimethods.
>
> > > But if you have parent -> child -> parent -> child ... relationships, I
> > > guess that you're building a tree made of mixins of maps and refs to maps
> > > ... and indeed this should bell some rings in your head if you haven't
> > > already carefully balanced alternative choices ...
>
> > > 2010/10/13 andrei 
>
> > > > How can I override print-method for a map, defined with defstruct?
>
> > > > I have to create object hierarchy: one map is a parent for another,
> > > > i.e. it holds link to a child, and another is a child for the first
> > > > one, i.e. holds link to a parent. When I try to print it, I get
> > > > StackOverflowError since printer tries recursively print objects:
>
> > > >  parent -> child -> parent -> child -> 
>
> > > > The best solution I see is to override print-method or str, so the
> > > > printing will go normally. I found this topic:
>
> > > >http://groups.google.com/group/clojure/browse_thread/thread/4a675222f...
>
> > > > which shows how to override print-method for objects defined by
> > > > deftype, but is there a way to do same trick for maps? Maybe it is
> > > > possible to add some special tag to object's meta? Or to redefine
> > > > print-method in the only namespace?
>
> > > > Or maybe I'm just looking at the wrong direction?
>
> > > > --
> > > > You received this message because you are subscribed to the Google
> > > > Groups "Clojure" group.
> > > > To post to this group, send email to clojure@googlegroups.com
> > > > Note that posts from new members are moderated - please be patient with
> > > > your first post.
> > > > To unsubscribe from this group, send email to
> > > > clojure+unsubscr...@googlegroups.com > > >  >
> > > > For more options, visit this group at
> > > >http://groups.google.com/group/clojure?hl=en

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To 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: precise numbers

2010-10-14 Thread Nicolas Oury
Another proof:

Let study the sequence sn = 0....9 , with n 9s.

Or s0= 0 and s(n+1) = sn + 9 / 10 ^n

lim sn = 0.9...
 and lim sn = 1.

so 
If I remember my meth correctly,
the number 0... does not exist.

This not a legal decimal sequence.
(Any decimal sequence finishing by .. is forbidden to allow a
one to one mapping between real numbers and
 decimal sequence.)

This kind of infinity is one of the reason equality is not devidable
on real numbers.

You can manipulate square root directly. For example by defining
numbers as a map from ratio to ratio.sqr
sqrt(5) is represented by {5 1}
sqrt(5) + 3. sqrt(2) by {5  1 , 2  3}
15 + sqrt(3) > {1 15, 3 1}

adding is just a reduce of one map into the other.
neg is a map.

multiplying is more complex. For each two pairs in the map
[a b] [c d], you check wether (ac) can be written as sqr(e).f
(For example 2 * 6 can be written as  sqr(2)*3)
If it is the case, you return [f (* e  b d)]
else you return [(* a c) (* b d)]

Dividing is more difficult.

I don't know if it is the most efficien way to do that, but it is the
easiest to code.

Best,

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