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

我是Clojure的新手,对函数式编程基本上是新手。我正在尝试创建一个字谜生成器,它可以生成所有可能的字符串重排。我想我应该对它进行概括,并对列表进行所有可能的重新排列

我的尝试:

(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))
列表项越多,问题就越严重

因此,有两个问题:

  • 这种额外的筑巢水平是从哪里来的?我试过各种版本的cons、concat、list等,但都没有用
  • 我该怎么做才能让这更“糟糕”
  • 试一试

    在get组合中


    原因:


    广告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