2016-11-02 55 views
0

我正在嘗試將一個句子列表傳遞給一個promise列表。如何使用索引變量遍歷兩個列表?

句顧着

(def sentences (repeatedly promise)) 
(future 
    (doseq [sentence (map deref sentences)] 
    (println sentence))) 

交付:

(doall (map deliver (nth sentences n) (parsedSentences))) 

例子:

n = 1 
parsedSentences = ["This is a sentence." "Is this a sentence?"] 

我想考績將parsedSentences中的每個條目都轉換爲相應的句子承諾。因爲我是很新的Clojure的我不能找到一種方法來向上計數n

我正在尋找一種方式做類似

deliver(nth sentences 1)("This is a sentence") 
deliver(nth sentences 2)("Is this a sentence?") 
... 
deliver(nth sentences n)(sentence n) 

所以基本上我正在尋找一個Clojure的方式來遍歷兩個列表使用索引變量或其他東西。

+3

你爲什麼不只是這兩個集合映射了嗎? (地圖提供句子parsedSentences)? – leetwinski

+0

@leetwinski謝謝我沒有意識到這是可能的 –

+0

另請參閱'map-indexed' http://clojuredocs.org/clojure.core/map-indexed –

回答

-1

地圖索引可能是你在找什麼。它需要的功能有兩個參數,如(fn [idx, el] (dosomething idx el)的行。我相信你也可以同時映射多個集合,並且每組元素將作爲一個元組被傳遞,如(c1e1, c2e1,..., cNe1)(c用於集合,e用於元素集合中的元素)。

clojure.core/map-indexed 
([f] [f coll]) 
    Returns a lazy sequence consisting of the result of applying f to 0 
    and the first item of coll, followed by applying f to 1 and the second 
    item in coll, etc, until coll is exhausted. Thus function f should 
    accept 2 arguments, index and item. Returns a stateful transducer when 
    no collection is provided. 
0

你已經自己半寫的答案,但你寫(nth sentences n)(一件事顯然是不可能的,因爲你知道n不在範圍內),而不是僅僅sentences

map功能是最常見的只有一個序列參數調用,但是當一個以上的稱之爲充當其他一些語言zipWith,返回[(f x0 y0) (f x1 y1) (f x2 y2) ...]。你甚至可以用零序參數調用map,然後它就是一個換能器。

所以,你只會寫

(map deliver sentences parsedSentences) 
+0

你是對的,並且在問我的問題後,我做了這件事,但在我的特殊情況下,這是行不通的,因爲我正在使用索引必須增長的無盡列表。 最後我用了下面的代碼。 (DEF句子(反覆承諾)) (DEF sentenceCounter 0) (doseq [句子parsedSentences](交付(第n個句子sentenceCounter)句)(DEF sentenceCounter(INC sentenceCounter))) 也許你可以把我的代碼在你的回答中,比我將你的答案標記爲正確的答案。 –