寻找路径方案

时间:2013-03-13 19:55:27

标签: path scheme racket

我是Scheme的新手,今天我遇到了以下无法解决的问题。我对表示文件系统的树的节点有以下表示:

目录的

(directory_name内容)
file_name for files
(directory_name null)表示空目录

例如,(“etc /”((“network /”(“interfaces”)))))是路径etc / network / interfaces的树。

我要做的是编写一个函数,将这种树和目录/文件名作为参数,并返回它的路径(如果有的话)。如果目录/文件不存在,则返回#f。

例如:

(define tree '("/"
               (("etc/" ("network/" ("interfaces")))
                ("root/" null))))

假设函数的名称是get-path,通过运行(get-path tree“interfaces”),它将输出“/ etc / network / interfaces”。

我想要的只是一个想法,如果你能给我一个,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

这是给你的答案。我使用符号而不是目录/文件的字符串,稍微改变了树格式。

(define tree '(root (etc (passwd) (profile)) (usr (bin) (lib))))

(define (get-path tree name)
  (define (reverse-if l) (and l (reverse l)))
  (reverse-if
   (let descending ((tree tree) (path '()))
     (and (not (null? tree))
          (let ((root (car tree))
                (subs (cdr tree)))
            (if (eq? root name)
                (cons root path)
                (let looking ((subs subs))
                  (and (not (null? subs))
                       (or (descending (car subs) (cons root path))
                           (looking (cdr subs)))))))))))

有一些结果:

> (get-path tree 'etc)
(root etc)
> (get-path tree 'bin)
(root usr bin)
> (get-path tree 'profile)
(root etc profile)
> (get-path tree 'foo)
#f
>