1

我有一个 LIST每行有一系列字符的文件。每行都标有一个类别,即“C”。例子:

C: w r t y i o p s d f g h j k l z b n m
V: a e i o u
E: n m ng

我想使用 打印 C、V 和 E(或者可能只是 C 和 V、C 和 E 等)的每个组合doseq,但一般来说,因为我在编译时不知道嵌套集合。

IE

"CV" [x y] (str x y ) 
"CVE" [x y z] (str x y z) 
"CVCV" [x y z a] (str x y z a)

我的代码word-generator.clj

(ns word-generator )
(use 'clojure.string)
(import 'java.io.File)
(use 'clojure.java.io)

(defn get-lines [fname]
  (with-open [r (reader fname)]
    (doall (line-seq r))))

(defn get-list [x lines]
  (first (remove nil?
  (for [num  (range (count lines)) ]
   (if (= (first(split (nth lines num) #"\s+")) x)
     (rest(split (nth lines num) #"\s+")))))))

(def sounds(get-lines "LIST")) ;; get the list


(def C (get-list "C:" sounds)) ;; map consonants 
(def V (get-list "V:" sounds)) ;; map vowels
(def E (get-list "E:" sounds)) ;; map end consonants
(def LI "CVE") ;; word structure 


(defn word-runner[carry args depth]
  (doseq [x C y V z E] (println (str x y z)))) ;; iterate and make the words

(defn runner[]
  ( (print "enter arg list: ")
    (def INPUT (read-line))
    (word-runner "" INPUT 0)))

我该如何实现word-runner,以便doseq在文件中找到的所有字符序列上进行嵌套循环 - 但在编译时不知道文件中的行数?

4

1 回答 1

2

这实际上是组合数学的问题,而不是循环。使用math.combinatoricscartesian-product库中的函数来解决您的问题。

;; alternative implementation of "word-runner"
(defn print-cartesian-products [& seqs] 
    (doseq [combs (apply cartesian-product seqs)] 
        (println (apply str combs))))
于 2012-10-27T02:43:56.497 回答