【问题标题】:Returning a value from a loop in Clojure从 Clojure 中的循环中返回一个值
【发布时间】:2020-11-05 00:27:46
【问题描述】:

我希望函数 (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) 在每次迭代中像{:distance "5 km" :duration "2 mins"} 这样返回(calculate-distance-matrix) 的值?

【问题讨论】:

  • 你不能用map代替doseq吗?我只在以下情况下使用doseq 1. doseq 的主体产生一些副作用,2. 我没有任何东西可以从那里返回

标签: loops google-maps clojure maps


【解决方案1】:

使用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)))

【讨论】:

    【解决方案2】:

    我会尝试用for 循环替换doseq。它将为(get-placetypes) 中的每个n 调用calculate-distance-matrix,然后将结果连接为一个序列:

    (defn string-place-typeII
      ""
      []
      (for [n (get-placetypes)]
        (calculate-distance-matrix 2 (define-context API-KEY) n))
      )
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • forv 是艾伦错字吗?
      猜你喜欢
      • 1970-01-01
      • 2015-06-23
      • 2016-01-30
      • 2020-10-05
      • 2016-03-23
      • 2013-04-25
      • 2023-03-10
      • 2014-04-10
      • 1970-01-01
      相关资源
      最近更新 更多