在字符串Clojure中查找元音索引

时间:2019-04-03 07:46:20

标签: clojure

我正在学习Clojure,并尝试在字符串中找到元音的索引

(def vowels [\a \e \i \o \u \y])
(let [word-index (interleave "aaded" (range))
      indexs (for [ [x i] (vector word-index)
                   :when (some #{x} vowels)]
               [i] )]
  (seq indexs))

但是,这给了我索引“ 0”,否则就错了。

6 个答案:

答案 0 :(得分:3)

> (def vowels #{\a \e \i \o \u})

> (filter some? (map #(when (vowels %1) %2) "aaded" (range)))
(0 1 3)

答案 1 :(得分:1)

您需要正确输入才能理解:

(let [word-index (interleave "aaded" (range))
      indexs (for [[x i] (partition 2 word-index)
                   :when (some #{x} vowels)]
               i)]
  (prn (seq indexs)))

;; => (0 1 3)

答案 2 :(得分:0)

当我们将序列映射到for循环的向量时,

interleave将给出一个惰性序列,我想我错过了索引。因此更改了实现,如下所示。

new Date()

哪个工作正常,如果有人可以更好地实施,请分享。谢谢。这将对我有所帮助。

答案 3 :(得分:0)

对于for函数的每次迭代,都会重复形成相同的哈希集。因此,最好在let块中进行定义。另外,我们可以直接使用hash-set作为函数,而我们不需要some函数。

(let [word-index (zipmap (range) "aaded")
      vowels-hash (into #{} [\a \e \i \o \u \y])
      indexs (for [[i x]  word-index
                   :when (vowels-hash x)]
               [i])]
  (flatten indexs))

答案 4 :(得分:0)

使用正则表达式的方法有些不同:

对于所有索引:

user> (let [m (re-matcher #"[aeiou]" "banedif")]
        (take-while identity (repeatedly #(when (re-find m) (.start m)))))
;;=> (1 3 5)

对于单个索引:

user> (let [m (re-matcher #"[aeiou]" "bfsendf")]
        (when (re-find m) (.start m)))
;;=> 3

user> (let [m (re-matcher #"[aeiou]" "bndf")]
        (when (re-find m) (.start m)))
;;=> nil

答案 5 :(得分:0)

@jas已经确定了这一点。添加我自己的内容以对中间步骤中发生的事情提供一些意见。

使用集合检查成员资格。然后是问题“这是元音吗?”会很快。

(def vowels (set "aeiouy"))
vowels
;; => #{\a \e \i \o \u \y}

我们可以过滤出元音,然后只获取索引

(defn vowel-indices-1 [word]
  (->> (map vector (range) word)      ; ([0 \h] [1 \e] [2 \l] ...)
       (filter (fn [[_ character]]    ; ([1 \e] [4 \o])
                 (contains? vowels character)))
       (map first)))                  ; (1 4)

(vowel-indices-1 "hello!")
;; => (1 4)

...或者我们可以按照您开始时的风格使用:when关键字(不知道,谢谢!)稍微花哨一些!

(defn vowel-indices-2 [word]
  (for [[i ch] (map vector (range) word)
        :when (contains? vowels ch)]
    i))

(vowel-indices-2 "hello!")
;; => (1 4)