2013-05-05 73 views
0

我试图建立一套函数来比较句子到另一个。所以我写了一个名为split-to-sentences函数,它像这样的输入:给定一个clojure向量,迭代删除1个元素

"This is a sentence. And so is this. And this one too."

和回报:

["This is a sentence" "And so is this" "And this one too."]

什么我挣扎是如何遍历这个向量,并得到不是当前值的项目。我试着用dropremove来唠叨,但还没有弄明白。

我想我可以做的一件事是在循环中使用firstrest,以及conj以前的值输出休息。

+0

你是指什么*不是当前值*的项目? – 2013-05-05 06:00:33

+0

向量中不是“current” – 2013-05-05 07:21:47

回答

2
(remove #{current-value} sentences-vector) 
+0

这是我正在使用的解决方案。非常感谢! – 2013-05-06 02:51:32

2

只需使用过滤器:

(filter #(not= current-value %) sentences-vector) 
0

的窍门是通过两次的句子变成reduce功能...

(def sentences ["abcd" "efg" "hijk" "lmnop" "qrs" "tuv" "wx" "y&z"]) 

(reduce 
    (fn [[prev [curr & foll]] _] 
    (let [aren't-current-value (concat prev foll)] 
     (println aren't-current-value) ;use it here 
     [(conj prev curr) foll])) 
    [[] sentences] 
    sentences) 

......一次,来看看下面的,而一旦迭代。

+0

的元素在第4行中更改为[[prev [curr&foll]]' – 2013-05-05 11:17:51

0

我相信你可能想是这样的功能:

(defn without-each [x] 
    (map (fn [i] (concat (subvec x 0 i) (subvec x (inc i)))) 
     (range (count x)))) 

使用方法如下:

>>> (def x ["foo" "bar" "baz"]) 
>>> (without-each x) 
==> (("bar" "baz") ("foo" "baz") ("foo" "bar")) 

返回的元素连接起来懒洋洋的,这就是为什么他们都没有载体。这是可取的,因为真向量级联(例如(进入b))是O(n)。

因为subvec使用与原始序列共享,所以不应该使用过量的内存。

0

,因为这两个载体上非常迅速操作您可以考虑使用subvecpop