我有一个文件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
我想使用doseq
打印C,V和E的每个组合(或者可能只是C和V,C和E等),但一般来说我不会在编译时知道嵌套集合时间。
即。
"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
对文件中找到的所有字符序列执行嵌套循环 - 但是在编译时不知道文件中的行数?
答案 0 :(得分:2)
这实际上是组合系统的一个问题,而不是循环。使用math.combinatorics库中的cartesian-product
功能解决您的问题。
;; alternative implementation of "word-runner"
(defn print-cartesian-products [& seqs]
(doseq [combs (apply cartesian-product seqs)]
(println (apply str combs))))