【问题标题】:stuck in finding index value in clojure [duplicate]卡在clojure中查找索引值[重复]
【发布时间】:2013-10-25 14:27:24
【问题描述】:

我想在clojure 中编写一个程序,它只返回我的函数中true 值的第一个索引值。我的代码在这里:

 (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 值?

【问题讨论】:

  • “stuck in”应该是你质疑的商标! :)
  • 最好你建议一些其他的标题:P
  • stackover 流程​​中的评论不适用于聊天和长时间讨论。
  • 不,这个问题没有重复,你可以看到我的 Winkler 的 cmets,这是我想要的不同的东西

标签: clojure indexing


【解决方案1】:
 (count (take-while not '(false false false true false false true false)))
 => 3

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

【讨论】:

  • 感谢您的建议,但它仅适用于存在 true 值的情况。对于true 不存在的情况,例如:(fun nil? []) 显示0 而它应该显示nil,如我的问题中所述。就像(func zero? [1 1 3 7]) 它返回4 但它应该返回nil,这意味着当true 不存在时,它只是计算元素的数量,因此它显示值04。所以这不是一个正确的答案。
  • 在上述情况下,您编辑的答案不会返回-1。我想我已经找到了答案,并会在所有测试用例结束后的几分钟内发布。
【解决方案2】:

您自己发布的答案似乎有点过于复杂。可以简化为:

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

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

【讨论】:

    【解决方案3】:

    好的,所以我自己找到了答案:

    (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) 
    

    【讨论】:

    • 所以,我在评论中发布的链接是正确的!
    • 好的,所以我没有看到后来的答案,但我没有从那里得到解决方案
    猜你喜欢
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    相关资源
    最近更新 更多