开发者

How to create a string list in Clojure?

I want to create a string list in Clojure equivalent to the following Java code:

List<String> cities = Arrays.asList(new String[] {"Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris","Stockholm" });

: but I am unsure abo开发者_开发百科ut the exact syntax


Strictly speaking, examples provided above will produce vectors. List can be produced in the following way:

(list "Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris","Stockholm")

or shorter:

'("Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris","Stockholm")

In some cases this difference could be important.


(def cities ["Berlin" "Brussels" "Helsinki" "Madrid" "Oslo" "Paris" "Stockholm"])

http://en.wikibooks.org/wiki/Clojure_Programming/Tutorials_and_Tips#Clojure_for_Java_Programmers


in general you can use the name of a collection you want to create as the function to create it (easy to remember eh?):

(vector     "Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris","Stockholm")
(hash-map   "Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris")
(sorted-map "Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris")
(array-map  "Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris")
(hash-set   "Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris" "Stockholm")
(sorted-set "Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris" "Stockholm")

or you can use into if you dont know in advance what type you will need to create.

(defn make-trip [trip cities]
    (into trip cities))

and pass it something like (make-trip #{"home"} ["Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris"])


None of these are actually equivalent to:

List<String> cities = Arrays.asList(new String[] {"Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris","Stockholm" });

This is much closer to an answer to what was actually asked:

user=> (java.util.ArrayList. [1 2 3])
#<ArrayList [1, 2, 3]>
user=> (.get (java.util.ArrayList. [1 2 3]) 0)
1


How about:

(def cities ["Berlin", "Brussels", "Helsinki", "Madrid", "Oslo", "Paris","Stockholm"])

The commas are optional.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜