2016-11-02 63 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))) 也许你可以把我的代码在你的回答中,比我将你的答案标记为正确的答案。 –