How is it possible to filter a list of directories via "directory-exists?"?

165 views Asked by At

I recently discovered a strange behaviour of racket: Whenever I try to filter a list of directories created via directory-list my REPL returns me an empty list, but when I try the same with an quasiquoted list my REPL returns a correctly filtered list.

My questions is now: Why it's impossible to filter a list of directories via directory-exists? and how it's possible to list only directories in racket?


Some examples:

When I use directory-exists? in combination with filter and directory-list the REPL returns me everytime an empty list:

(filter directory-exists? (map path->complete-path 
                               (directory-list (expand-user-path "~"))))
;; '()

Now, when I filter an quasiquoted list like in the following example. The REPL returns a correct filtered list, with all existing directories (without the imaginary directory ~/blablubb)

(filter directory-exists? 
        (map path->complete-path `(,(path->complete-path (expand-user-path "~/documents")) 
                                   ,(expand-user-path "~/blablubb" )))) 
;; '(#<path:/home/niklas/documents>)
2

There are 2 answers

1
Ryan Culpepper On BEST ANSWER

directory-list returns relative paths by default, which are later implicitly resolved with respect to the (current-directory), which might be different from the directory you passed to directory-list.

Kind of like this:

~ $ ls dir
file1 subdir2
~ $ cat file1
cat: file1: No such file or directory

From the current directory, the file is at path dir/file1, not just file1.

One solution is to ask directory-list to include the directory in the paths returned:

(directory-list the-dir #:build? #t)

Then if the-dir is a complete path, the results will also be complete paths.

2
soegaard On

FWIW running your snippet

(filter directory-exists? 
   (map path->complete-path 
      (directory-list (expand-user-path "~"))))

on OS X gives me a list of directories.

You are clearly seeing something else.

Two questions:

   1. What is the result of:

   (map path->complete-path 
      (directory-list (expand-user-path "~"))))


   2. Which OS are you using?