簡體   English   中英

(clojure.core / seq)而不是列表

[英](clojure.core/seq) instead of list

我不明白為什么我會收到而不是正常列表(clojure.core / seq)。 我的密碼

(defn del-list [arg-list lvl] (do
                                (cond
                                 (= lvl 1) (remove seq? arg-list)
                                 :else (map #(if (seq? %)
                                               (del-list % (- lvl 1))
                                               %
                                               ) arg-list)
                                )
                            ))
(println (del-list `(1 2 3 `(1 2 `(1 2 3) 3) 1 2 3) 2))
;result=> (1 2 3 (clojure.core/seq) 1 2 3)

為什么會這樣呢? 我不知道搜索的有效性如何,Google的所有鏈接都指向指向seqseq?文檔seq?

就像@ClojureMostly在評論中說的那樣,不要使用bacticks,請使用單引號。 也不要嵌套它們,一個就足夠了。

因此,像這樣調用您的函數:

(println (del-list '(1 2 3 (1 2 (1 2 3) 3) 1 2 3) 2))

將解決您眼前的問題。

再深入一點,單引號(僅稱為引號)和反引號(稱為語法引號)之間存在一些差異。

在引用某些內容時,您說的是只需要數據結構,而不應將其視為代碼。 在clojure中,代碼是數據,因此(+ 1 2)是一個列表,其中包含一個符號和兩個數字,當作為代碼評估時,等於3。因此, (+ 1 2) => 3'(+ 1 2) => (+ 1 2)

語法quote相似,但是它查找事物的名稱空間,您可以取消對內部事物的引用。 這對於編寫宏很有用。

;; Looks up the namespaces of symbols to avoid the problem of variable capture
`(+ 1 2) ;=> (clojure.core/+ 1 2)

;; You can unquote parts of the expression.
;; ~ is unquote ~@ is unqoute splicing
;; That should give you the vocabulary to google this.
`(+ 1 2 3 ~(* 2 2)) ;=> (clojure.core/+ 1 2 3 4)

嵌套引號從來都不是您想要的。 (除非您交替使用引號和取消引號,否則即使這樣通常也會造成混淆)

在Clojure中,除非您特別想要數據的鏈表的某些屬性,否則通常將順序事物表示為矢量[1 2 3] (O(n)隨機訪問,在末尾增加)。 (就像表示堆棧一樣,列表有效地添加和刪除了第一個元素。)

(defn del-list [arg-list lvl]
  ;; You don't need the do, there's an implicit do in many special forms
  ;; like let, fn and defn
  ;; Also you only had one thing in your do, in that case it doesn't do anything

  ;; There's only one condition, so I'd use if instead of cond
  (if (= lvl 1)

    ;; And, like someone mentioned in the comments,
    ;; what you probably want is sequential? instead of seq?
    (remove sequential? arg-list)
    (map #(if (sequential? %)
            (del-list % (dec lvl)) ; dec stands for decrement
            %)
         arg-list)))


;; This works
(println (del-list '(1 2 3 (1 2 (1 2 3) 3) 1 2 3) 2))

;; But this is more idiomatic (modulo specific reasons to prefer lists)
(println (del-list [1 2 3 [1 2 [1 2 3] 3] 1 2 3] 2))

;; If you change map to mapv, and wrap remove with vec it will return vectors
(defn del-vec [arg-vec lvl]
  (if (= lvl 1)
    (vec (remove sequential? arg-vec))
    (mapv #(if (sequential? %)
             (del-vec % (dec lvl)) ; dec stands for decrement
             %)
          arg-vec)))

(println (del-vec [1 2 3 [1 2 [1 2 3] 3] 1 2 3] 2))

;; But most of the time you don't care about the specific type of sequential things

至於您的實際問題,為什么出現clojure.core / seq,我不知道。 那不是您使用報價的方式,所以它從來沒有出現過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM