2013-03-30 84 views
0

我有以下代碼:調用映射功能似乎並沒有做任何事情

(defn remove-folder [file] 
    (do 
     (println "Called with file " (.getName file)) 
     (if (.isDirectory file) 
      (do 
      (println (.getName file) " is directory") 
      (def children (.listFiles file)) 
      (println "Number of children " (count children)) 
      (map remove-folder children) 
      (delete-file file))) 
      (do 
      (println (.getName file) " is file") 
      (delete-file file) 
     ))) 

我的問題是,線(地圖中刪除文件夾兒童)似乎並沒有工作。在我的輸出中,我希望能夠通過夾層結構旅行,但它似乎留在第一層。

我想我已經犯了一些愚蠢的錯誤,但我現在花了幾個小時,似乎並沒有接近一個解決方案。

+0

['def'](http://clojure.org/special_forms#def)創建在當前名稱空間中的全局變量。對於本地綁定,您應該使用['let'](http://clojuredocs.org/clojure_core/clojure.core/let)。 –

+0

@LeonidBeschastny原始版本在與地圖相同的一行中調用了.listFiles。問題是調用映射似乎沒有發生任何遞歸調用。 – Roland

回答

2

正如@ponzao所說,map是懶惰的。

但無論如何,我不認爲這是一個好主意,使用map只是爲了得到副作用和「放棄」結果。就個人而言,我會用doseq來代替,因爲它提示我期待副作用。

(defn remove-folder [file] 
    (do 
     (println "Called with file " (.getName file)) 
     (if (.isDirectory file) 
      (do 
      (println (.getName file) " is directory") 
      (def children (.listFiles file)) 
      (println "Number of children " (count children)) 
      (doseq [c children] 
      (remove-folder c)) 
      (delete-file file))) 
      (do 
      (println (.getName file) " is file") 
      (delete-file file) 
     ))) 
+0

完美工作 – Roland

3

map很懶,把它包裝在doall中來強制評估,如下:(doall (map remove-folder children))

0

你爲什麼不在線兒童,擺脫高清?似乎你並不想在當前的命名空間中創建一個全局綁定。你無意中引入了副作用。

函數名稱remove-folder不會告訴我們函數應該做什麼。參數名稱文件沒有描述可以預期什麼樣的參數。但我明白這是一種探索性的代碼。

乾杯 -

相關問題