longs functiooon cloj
I'm trying to use the longs
function, but it's not working:
(println (longs 1 2 3))
A开发者_如何学JAVAny examples?
The description in the site is not very good, which is why I'm having problems http://clojure.org/cheatsheet
Thanks
You're question is woefully incomplete, but I'll take a stab at it anyway.
The documentation for longs
says:
Usage: (longs xs)
That means, it's expecting one argument (named xs
in this example). You're passing it three arguments.
The documentation for longs
continues thus:
Casts to
long[]
Casting means: It doesn't change xs, it simply checks that it is an array of primitive long
and then make this information available to the compiler. Basically, wrapping an expression that produces a long[]
in (longs ...)
is a type hint for Clojure so that it doesn't have to use reflection at runtime to resolve a method call using that value as an argument:
// Suppose we have a java class
class JavaClass {
static long[] getSomeLongs() { ... }
static long sum(long[] numbers) { ... }
static float sum(float[] numbers) { ... }
}
;; And this Clojure code:
(defn numbers [] (JavaClass/getSomeLongs))
(JavaClass/sum (numbers))
Clojure is dynamically typed, so when it compiles the second line, it won't know that (numbers) returns an array of long. It will have to wait until run time and then look up the correct JavaClass/sum method using reflection. This is expensive.
The solution is to give the Clojure compiler a hint about the type of (numbers). That way it can choose the correct method to call at compile time, resulting in a faster running program:
(JavaClass/sum (longs (numbers)))
But, judging from your woefully incomplete question, that's probably not what you were expecting when you reached for longs
. It seems you were hoping it would create an array of longs from the arguments you gave it. If that's what you want then use this:
(into-array Long/TYPE [1 2 3])
But, you're likely to be disappointed by the results of printing it:
user=> (println (into-array Long/TYPE [1 2 3]))
#<long[] [J@2321b59a>
That's what Java gives back when you ask it to convert an array into a String, so that's what Clojure prints. If you want to see the contents of the array printed back, you need to make a sequence:
user=> (println (seq (into-array Long/TYPE [1 2 3])))
(1 2 3)
精彩评论