从Clojure中的循环返回一个值

时间:2017-01-23 05:18:56

标签: list google-maps loops clojure maps

我希望函数(string-place-typeII)能够像(calculate-distance-matrix)这样在每个循环中返回{:distance "5 km" :duration "2 mins"}的值,或者更好地将其传递给某个变量括在{}中,所以我可以在循环结束时返回所有内容。

功能列表:

(defn get-placetypes
  ""
  []  (into-array (PlaceType/values )) )

(defn get-all-placetypes
  ""
  [x]
  (def my-vector (get-placetypes))
  (let [[& the-rest] my-vector]
    (nth the-rest x) ))

(defn string-place-typeII
  ""
  []
  (doseq [n (get-placetypes)]
    (calculate-distance-matrix 2 (define-context API-KEY) n))
  )
(defn calculate-distance-matrix
  ""
  [property-id context place-type]
  ;(def nearby-search-fucntion  )
  (let [r (. (. (. (DistanceMatrixApi/newRequest
                     context)
                   origins (into-array [(coordinates->keys property-id context)] ))
                destinations (into-array [(m/latlng (do-nearby-search property-id context place-type))]))  await)]

    {:distance (-> r
                   .rows
                   first
                   .elements
                   first
                   .distance
                   .humanReadable)
     :duration (-> r
                   .rows
                   first
                   .elements
                   first
                   .duration
                   .humanReadable)})

如何在每次迭代时让(string-place-typeII)像这样(calculate-distance-matrix)返回{:distance "5 km" :duration "2 mins"}的值?

3 个答案:

答案 0 :(得分:3)

使用map

https://clojuredocs.org/clojure.core/map

(defn string-place-typeII
  []
  (map (fn [n] (calculate-distance-matrix 2 (define-context API-KEY) n))
       (get-place-types)))

答案 1 :(得分:0)

请为the Clojure Cheatsheet加上书签,并始终打开浏览器标签。

我认为您正在寻找for函数而不是doseqdoseq用于副作用(例如打印,数据库等)并始终返回nilfor每次循环返回一个项目。

以下是您可以做的事情的概述:

(defn calc_dist [n]
  { :dist (* 2 n) :dur (* 3 n) } )

(defn caller-1 []
  (doseq [n (range 5)]
    (calc_dist n)))

(defn caller-2 []
  (for [n (range 5)]
    (calc_dist n)))

(caller-1) => nil
(caller-2) => [{:dist 0, :dur 0} {:dist 2, :dur 3} {:dist 4, :dur 6} {:dist 6, :dur 9} {:dist 8, :dur 12}]

关于(let [r ...)表达式,请参阅the clojure.org section on Java Interop。我相信你会发现the .. special form更容易阅读。您还应该考虑the doto function

答案 2 :(得分:0)

我会尝试用qmake循环替换doseq。它将为for中的每个calculate-distance-matrix调用n,然后结果将作为序列加入:

(get-placetypes)