【问题标题】:Returning positions of an element Clojure返回元素 Clojure 的位置
【发布时间】:2016-02-05 14:13:16
【问题描述】:

我正在尝试找到解决我目前面临的问题的方法,我已经尝试并尝试让这个工作但无济于事。我正在尝试扫描包含数据的列表,然后如果找到则返回数据的位置。

例如,如果我运行这个:

(ind 'p '(l m n o p o p))

然后我会得到一个返回值......

==>  4 6  

因为它在那些位置找到了数据。

我已经接近我之前想用这个解决方案想要的东西,但我无法让它运行。谁能帮我弄清楚我的功能是怎么回事?据我所知,它应该可以工作,但我无法弄清楚为什么它不是?

(defn ind
([choice list emptylist x]
(let [x (count list)])
(if (= (x) 0)
  nil)
(if (= (first list) item)
  (ind item (rest list) (cons x emptylist) (dec x))
  (ind item (rest list) emptylist (dec x))
  )
 )
)

我试图做的是循环遍历列表,直到它遇到一个值并将其添加到空列表中,一旦它循环通过返回空列表。

【问题讨论】:

标签: recursion clojure functional-programming lisp iteration


【解决方案1】:

我发现 Clojure 中有一个名为 keep-indexed 的内置函数。

所以你可以简单地这样做:

(keep-indexed (fn [idx elm] (if (= 'p elm) idx)) '(l m n o p o p))
; return (4 6)

【讨论】:

  • 建议你把它框定为必需的函数:(defn ind [x coll] (keep-indexed (fn [idx elm] (if (= x elm) idx)) coll))
  • 哇,我以前从未见过这个功能。
【解决方案2】:

这是一个我认为更简单的解决方案:

(defn find-index 
  "Returns a seq of the indexes of the supplied collection."
  [values target]
  (let [indexes           (range (count values))
        val-idx-tuples    (map vector values indexes) 
        found-tuples      (filter #(= target (first %)) val-idx-tuples)
        found-indexes     (vec (map second found-tuples)) ]
    found-indexes))

(println (find-index '(l m n o p o p) 'p ))

;=> [4 6]

【讨论】:

  • 你可以不用indexes。只需说(let [val-idx-tuples (map vector values (range)) ... ] ...)map 在任何集合用完时终止。您可以使用map-indexed 而不是map 获得类似的效果。我也会省略最后的vec。那么整个事情就是懒惰的,所以客户可以决定如何以及何时实现它。
【解决方案3】:

虽然我更喜欢@chanal's approach,但你可以编写你想要的函数如下:

(defn ind [x coll]
  (loop [ans [], coll coll, n 0]
    (if-let [[y & ys] (seq coll)]
      (recur (if (= x y) (conj ans n) ans) ys (inc n))
      ans)))

(ind 'p '(l m n o p o p))
;[4 6]

这里使用了几个成语来使其简洁:

  • if-letlet 中包含if
  • 解构形式[y & ys] 包含对firstrest 的调用。
  • if 表单下推到recur 可以避免重复。

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多