2015-08-17 63 views
0

任何方式我都可以通過以下代碼獲得更多的慣用Clojure。我知道我錯過了關於解構的一些東西。至少我可以說我理解當前的代碼。我的第一個誘惑是使用doseq,然後填充hash-map,但我確信map是解決方案。改善此Clojure代碼以獲得更多習慣用法

的代碼讀取一個CSV文件 - 由最高得分排序

Name,Department,Score 
Rohan,IT,8 
Bob,Sales,6 
Tom,IT,9 
Jane,Accounting,3 
Mary,Sales,9 
Harry,IT,8 
Frodo,Marketing,8 
Bilbo,Accounting,10 

和將輸出行。簡單!

(def file "scores.csv") 

(defn list-of-vecs [] 
    (let [file-str (slurp file)] 
    (let [lines (clojure.string/split-lines file-str)] 
     (next (map #(clojure.string/split % #",") lines))))) 

(defn list-of-maps [] 
    (map (fn [n] {:name (n 0), :department (n 1), :score (Integer/parseInt (n 2))}) 
     (list-of-vecs))) 

(defn sorted-list [] 
    (reverse (sort-by :score (list-of-maps)))) 

(defn print-high-scores [] 
    (prn "Name","Department","Score") 
    (map (fn [m] (prn (m :name) (m :department) (m :score))) (sorted-list))) 

任何反饋將不勝感激,包括在縮進。

另外我很驚訝的表現(跑在裏面)。的8行25K線

parse-csv.core=> (time print-high-scores) 
"Elapsed time: 0.026059 msecs" 

CSV文件

CSV文件

parse-csv.core=> (time print-high-scores) 
"Elapsed time: 0.025636 msecs" 
+0

還是我使用'time'不正確? –

+2

更實際可靠的方法是使用CSV解析庫。如果(引號)的值變成逗號,盲目地用逗號分割將會失敗。你的情況是否可行?我認爲這個問題更多地屬於CodeReview.SE。你並沒有真正解決問題,你正在尋找改進代碼的方法。 –

+1

Clojure有一個官方的CSV閱讀器:https://github.com/clojure/data.csv然後做1:用一個簡單的'map'解析整數。 2:'排序' – ClojureMostly

回答

1

做你的(time print-high-scores)實際打印什麼?

Or am I using time incorrectly

我認爲你是正確的期運用,但測量錯誤的事情。

我的方法:

; read file - drop header line 
(def input 
    (rest (line-seq (clojure.java.io/reader "inputfilename")))) 

; top ten 
(def top-ten 
    (take 10 (time (sort-by 
       #(- (Integer/parseInt (nth % 2))) ; negate so highest first 
       (map (fn [line] 
        (clojure.string/split line #",")) input))))) 
; 10 lines "Elapsed time: 0.469539 msecs" 
; 25k lines "Elapsed time: 68.157863 msecs" 

; print - sideeffect 
(time (doseq [e (doall top-ten)] 
    (print e "\n"))) 

"Elapsed time: 0.02804 msecs" 
[Bilbo Accounting 10] 
[Tom IT 9] 
[Mary Sales 9] 
[Rohan IT 8] 
[Harry IT 8] 
[Frodo Marketing 8] 
[Bob Sales 6] 
[Jane Accounting 3] 
nil