2013-10-25 42 views
-1

我想写一个程序clojure只会返回我的函数的第一个索引值true值。我的代码放在这里:卡住寻找clojure中的索引值

(defn func [f x] (map f x)) 

所以,如果我给的值,如:

(func zero? [1 1 1 0 3 7 0 2]) 

它给我:

(false false false true false false true false) 

,如果我给:

(func (fn [n] (= n 6)) [:cat :dog :six :blorg 6]) 

返回:

(false false false false true) 

但是,我想要的是index valuefirst true。像

(func zero? [1 1 1 0 3 7 0 2]) => 3 (desired result) 
(func (fn [n] (= n 6)) [:cat :dog :six :blorg 6]) => 4 (desired result) 
(func zero? [1 1 3 7 2]) => nil (desired result) 

可有人建议如何获得truefirst index价值?

+2

“卡在”应该是您的商标质疑! :) – Chiron

+0

更好的你建议一些其他的标题:P – user227666

+0

在stackover流中的评论不适用于聊天和漫长的讨论。 – Chiron

回答

-1

好了,我发现我的问题本身就是答案:

(defn indices [pred coll] 
    (keep-indexed #(when (pred %2) %1) coll)) 

    (defn tun [f x] 
    (first (indices true? 
       (vec (map f x))))) 

,如果你这样做:

(tun zero? [1 1 3 7 2]) => nil (the exact desired result) 
+0

因此,我在评论中发布的链接是正确的! – Chiron

+0

好,所以我没有看到后面的答案,但我没有从那里得到解决方案 – user227666

1
(count (take-while not '(false false false true false false true false))) 
=> 3 

(.indexOf '(false true) true) 
=> 1 
+0

谢谢你的建议,但它适用于只有'true'值存在的情况。对于'true'不存在的情况:'(fun nil?[])'显示为'0',而它应该显示'nil',正如我的问题所述。就像'(func zero?[1 1 3 7])'它返回'4',但它应该返回'nil',这意味着当'true'不存在时它只计算元素的数量,所以它显示值'0'和'4'。所以这不是一个正确的答案。 – user227666

+0

鉴于上述情况,没有编辑的答案返回“-1”。我想我已经想出了答案,并且会在所有测试用例的几分钟后发布。 – user227666

0

您发布自己的答案似乎略过于复杂。它可以被简化成这样:

(defn first-indexed [pred coll] 
    (first (keep-indexed (fn [idx itm] 
         (when (pred itm) 
          idx)) 
         coll))) 

tuntrue? (vec (map部分是不必要的。