我需要在单个线程中编写Clojure中的merge-sort算法的实现,并使用带有2,4,8,16和32个线程的并行选项。
程序将从文本文件中读取大量整数(100万),并将它们放入列表中进行排序
我是Clojure和函数式编程的新手。
我刚刚编写了阅读文件的代码......
(use 'clojure.java.io)
(defn get-lines [fname]
(with-open [r (reader fname)]
(doall (map read-string (line-seq r)))))
(def numbers (get-lines "numbers.dat"))
...找到单线程实现。
但我无法实现并行算法。这似乎超出了我的范围
有人能帮助我吗?
答案 0 :(得分:1)
如果有人在寻找......
(use 'clojure.java.io)
(defn get-lines [fname]
(with-open [r (reader fname)]
(doall (map read-string (line-seq r)))))
(def numbers (get-lines "numbers.dat"))
(defn merge-lists [left right]
(loop [head [] L left R right]
(if (empty? L) (concat head R)
(if (empty? R) (concat head L)
(if (> (first L) (first R))
(recur (conj head (first R)) L (rest R))
(recur (conj head (first L)) (rest L) R))))))
(defn naive-merge-sort [list]
(if (< (count list) 2) list
(apply merge-lists
(map naive-merge-sort
(split-at (/ (count list) 2) list)))))
(defn parallel-merge-sort-2 [list]
(if (< (count list) 2) list
(apply merge-lists
(pmap naive-merge-sort
(split-at (/ (count list) 2) list)))))
(defn parallel-merge-sort-4 [list]
(if (< (count list) 2) list
(apply merge-lists
(pmap parallel-merge-sort-2
(split-at (/ (count list) 2) list)))))
(defn parallel-merge-sort-8 [list]
(if (< (count list) 2) list
(apply merge-lists
(pmap parallel-merge-sort-4
(split-at (/ (count list) 2) list)))))
(defn parallel-merge-sort-16 [list]
(if (< (count list) 2) list
(apply merge-lists
(pmap parallel-merge-sort-8
(split-at (/ (count list) 2) list)))))
(defn parallel-merge-sort-32 [list]
(if (< (count list) 2) list
(apply merge-lists
(pmap parallel-merge-sort-16
(split-at (/ (count list) 2) list)))))
naive-merge-sort是单线程实现。并行实现将输入列表分成2-32个块,这些块使用naive-merge-sort进行排序。
答案 1 :(得分:0)
这听起来很像家庭作业(如评论者所说),所以我对提供详细答案犹豫不决。我可以告诉你,你想要在Clojure中研究不同类型的并发性。从最简单到最复杂的顺序,您可能要考虑的一些方法是pmap,futures和core.async。我建议您查看basic docs for pmap, Clojure For the Brave and True 的章节concurrency和core.async以及clojure。 org&#39; page about concurrency