Gustav Bertram
Gustav Bertram

Reputation: 14911

Listing files in two separate directories in Clojure

I'm trying to get Overtone to work on my Windows 10 machine. I seem to have found a bug in the code that attempts to start the synthesizer server. Overtone depends on SuperCollider, and it looks up the location of scsynth.exe by looking at where SuperCollider is installed. But the code that is supposed to check both C:\Program Files and C:\Program Files (x86) only checks the first one that exists instead of both:

(import java.io File)
(let [p-files-dir (System/getenv "PROGRAMFILES(X86)")
      p-files-dir (or p-files-dir (System/getenv "PROGRAMFILES"))
      p-files-dir (File. p-files-dir)
      p-files     (map str (.listFiles p-files-dir))
      p-files])

In my case, both directories exist, but SuperCollider only exists in C:\Program Files. The snippet above only lists files in C:\Program Files (x86).

How do I get this code to return all of the files in both directories, and not break when one doesn't exist?

Upvotes: 2

Views: 65

Answers (1)

Chris Murphy
Chris Murphy

Reputation: 6509

You were not returning something from your let form, so notice here p-files is outside the []:

(let [p-files-dir-1 (System/getenv "PROGRAMFILES(X86)")
      p-files-dir-2 (System/getenv "PROGRAMFILES")
      p-files-dir-file-1 (File. p-files-dir-1)
      p-files-dir-file-2 (File. p-files-dir-2)
      p-files (map str (concat 
                         (.listFiles p-files-dir-file-1) 
                         (.listFiles p-files-dir-file-2)))]
  p-files)

The answer to your question is that you can just concat together two lists, after which you would need to filter for the file.

Here's a shorter answer (the map str is not strictly necessary here):

(map str (concat ["a" "b" "c"] ["d" "e" "f"]))
;; => ("a" "b" "c" "d" "e" "f")

To remove all the temporary variables you could use this function:

(defn env-files [file-name]
  (some-> file-name
          System/getenv
          File.
          .listFiles))

Then the code becomes:

(map str (concat
             (env-files "PROGRAMFILES(X86)")
             (env-files "PROGRAMFILES")))

Upvotes: 4

Related Questions