r/mit6824clojure • • Jul 12 '20

web crawler spoilers Spoiler

The gist below contains two solutions to the webcrawler written in clojure by me and another by adrian smith who was kind enough to give me some pointers.

clojure webcrawlers

2 Upvotes

1 comment sorted by

1

u/ErnestoGarciaGarcia Aug 02 '20

Both implementations are sequential in the end.

Here an implementation from my side:

(defprotocol Fetcher
  (fetch [this url]))

(defn crawl [url depth fetcher done-fn]
  (let [visited (atom #{})
        pending (atom 0)
        crawl-impl 
        (fn rec [url depth]
          (swap! pending inc)
          (go
            (try
              (when (pos? depth)
                (let [{:keys [body urls error]} (fetch fetcher url)]
                  (println "fetched:" url (if error error body))
                  (when-not error
                    (swap! visited conj url)
                    (dorun
                      (for [u urls
                            :when (not (@visited u))]
                        (rec u (dec depth)))))))
              (finally
                (let [p (swap! pending dec)]
                  (when (and (= p 0) done-fn)
                    (done-fn)))))))]
    (crawl-impl url depth)))

(defn main []
  (crawl "https://clojure.org/" 4 fetcher #(println "done!")))