什么是创建Clojure函数的正确方法,该函数返回基于另一个序列的新序列?

时间:2012-04-20 10:13:31

标签: clojure

为什么你必须在get-word-id中使用“first”,以及正确的方法是什么?

(defn parts-of-speech []
  (lazy-seq (. POS values)))

(defn index-words [pos]
  (iterator-seq (. dict getIndexWordIterator pos)))

(defn word-ids [word]
  (lazy-seq (. word getWordIDs)))

(defn get-word [word-id]
  (. dict getWord word-id))

(defn get-index-words []
  (lazy-seq (map index-words (parts-of-speech))))

(defn get-word-ids []
  (lazy-seq (map word-ids (first (get-index-words)))))

;; this works, but why do you have to use "first" in get-word-ids?
(doseq [word-id (get-word-ids)]
  (println word-id))

2 个答案:

答案 0 :(得分:4)

简短回答:删除对lazy-seq的所有引用。

至于你原来的问题,即使它不是lazy-seq的惯用法,也值得解释。你必须先使用,因为get-word-ids函数返回一个带有一个条目的惰性序列。该条目是您正在寻找的懒惰序列。

看起来像这样

( (word1 word2 word3) )

所以首先返回你想要的序列:

(word1 word2 word3)

<小时/> 您使用lazy-seq的唯一时间很可能是这种模式:

(lazy-seq (cons :something (function-call :produces :the :next :element)))

我从未见过任何其他模式中使用的lazy-seq。 lazy-seq的目的是生成新的原始数据序列。如果存在生成数据的代码,那么使用iterate mapfor之类的东西来生成懒惰序列几乎总是更好。

答案 1 :(得分:1)

这似乎不对:

(defn get-index-words []
  (lazy-seq (map index-words (parts-of-speech))))

(index-words pos)返回一个seq。这就是为什么你需要一个(第一个)get-word-id。

map也已经很懒了,所以没有必要在lazy-seq中包含一个(map ...),如果map 不是,那么在map中使用lazy-seq几乎是没有意义的/ em>懒惰。如果你在clojure中读了更多关于(懒惰)序列的话,它可能会有用。