[英]How can i loop through a Collection in Clojure?
我有一個矩陣,我想打印它的行。 我試圖像這樣實現它,但我不知道如何循環並獲取其他元素!
(defn p! [args]
(println (first args))
(drop args))
(p! [[1 2] [3 4]]) --> [1 2]
the output should look like this
;; 12
;; 34
我建議使用core.matrix工具來完成這項任務。 它擁有成熟且久經考驗的 API。 除此之外,它還為您提供了一個pm
function,它可以漂亮地打印一個矩陣並接受一個自定義元素formatter
作為參數。
您可能會發現它的實現很有趣,因為它可以讓您了解打印類似數組的結構。 (TL;DR:它使用遞歸算法來處理它,該算法大量使用了dotimes
fn。)
有了這個庫,你最終可能會實現你的p!
fn 像這樣:
(require '[clojure.core.matrix :as mx])
(defn p! [args]
(mx/pm (mx/matrix args)))
(p! [[1 2] [3 4]])
[[1 2]
[3 4]]
=> nil
如果您想保持簡單和/或省略括號,那么最簡單的實現將遵循以下幾行:
(defn p! [args]
(doseq [row args]
(println (clojure.string/join " " row))))
(p! [[1 2] [3 4]])
1 2
3 4
=> nil
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.