Clojure 这个名单是从哪里来的?
我是Clojure的新手,对函数式编程基本上是新手。我正在尝试创建一个字谜生成器,它可以生成所有可能的字符串重排。我想我应该对它进行概括,并对列表进行所有可能的重新排列 我的尝试:Clojure 这个名单是从哪里来的?,clojure,Clojure,我是Clojure的新手,对函数式编程基本上是新手。我正在尝试创建一个字谜生成器,它可以生成所有可能的字符串重排。我想我应该对它进行概括,并对列表进行所有可能的重新排列 我的尝试: (defn pairs [items] (list (list (first items) (last items)) (list (last items) (first items)))) (defn prepend-to-list-or-item [item coll] (if (col
(defn pairs [items]
(list (list (first items) (last items))
(list (last items) (first items))))
(defn prepend-to-list-or-item [item coll]
(if (coll? coll)
(map #(cons item %) coll)
(list item coll)))
(defn remove-one [coll item]
(let [[n m]
(split-with (partial not= item) coll)]
(concat n (rest m))))
(defn get-combinations [items]
(cond (= 0 (count items)) nil
(= 1 (count items)) items
(= 2 (count items)) (pairs items)
:else
(map #(prepend-to-list-or-item % (get-combinations (remove-one items %))) items)))
我遇到的问题是,我得到的列表嵌套得太深了。我得到的结果是:
clojure-test.combinations> (clojure.pprint/pprint (get-combinations '(\a \b \c)))
(((\a \b \c) (\a \c \b))
((\b \a \c) (\b \c \a))
((\c \a \b) (\c \b \a)))
nil
我的期望输出:
((\a \b \c) (\a \c \b) (\b \a \c) (\b \c \a) (\c \a \b) (\c \b \a))
列表项越多,问题就越严重
因此,有两个问题:
原因:
广告2。) 我将
coll
改为chars
并将item
改为char
——这仅供我理解
您可以简化删除一个
(如果我读对了,您确实希望coll不带项目,这正是过滤器的用途)
获取组合,更具可读性的case语句
(let [char-count (count chars)]
(case char-count
0 nil
1 chars
2 (pairs chars)
(mapcat
工作完美!谢谢,伙计。我想我需要玩map
和更多的朋友。用例看起来更干净。我无法使用过滤器
,因为我需要保留重复项。我从中获取了与分离的解决方案我能做些什么来让这个更“clojure?”
-这通常被称为“更惯用”-如“我如何让这个clojure代码更惯用?”
(map list-producing-function a-list) ; will give you a list of lists
(defn remove-one [chars char]
(filter (partial not= char) chars))
(let [char-count (count chars)]
(case char-count
0 nil
1 chars
2 (pairs chars)
(mapcat