在常见的lisp中加入一系列路径组件

eal*_*nso 0 sbcl common-lisp

如何在常见的lisp中加入一系列路径组件?

在python中,我能做到,

`os.path.join("/home/", username, "dira", "dirb", "dirc");`
Run Code Online (Sandbox Code Playgroud)

常见的lisp中的等价物是什么?

当然我可以编写自己的函数,但我怀疑我应该能够使用内置函数.

Dir*_*irk 6

如果你坚持使用字符串来表示路径名,那么除了滚动自己的解决方案之外,似乎没有内置的解决方案.

(defun join-strings (list &key (separator "/") (force-leading nil))
  (let* ((length (length list))
         (separator-size (length separator))
         (text-size (reduce #'+ (mapcar #'length list) :initial-value 0))
         (size (+ text-size (* separator-size (if force-leading length (1- length)))))
         (buffer (make-string size)))
    (flet ((copy-to (position string)
             (loop
               :with wp := position
               :for char :across string 
               :do (setf (char buffer (prog1 wp (incf wp))) char)
               :finally (return wp))))
      (loop
        :with wp := 0
        :for string :in list
        :do (when (or force-leading (plusp wp)) (setf wp (copy-to wp separator)))
            (setf wp (copy-to wp string)))
      buffer)))

(join-strings '("home" "kurt" "source" "file.txt") :force-leading t)
==> "/home/kurt/source/file.txt"
Run Code Online (Sandbox Code Playgroud)

但是,如果您可以使用路径名,那么您可以执行以下操作:

(merge-pathnames #P"subdir1/subdir2/file.type" #P"/usr/share/my-app")
==> #P"/usr/share/my-app/subdir1/subdir2/file.type"
Run Code Online (Sandbox Code Playgroud)

pathname API还提供了以符号方式操作路径名,提取路径名的组件等功能:

(pathname-directory #P"subdir1/subdir2/file.type")
==> '(:relative "subdir1" "subdir2")

(pathname-name #P"subdir1/subdir2/file.type")
==> "file"

(pathname-type #P"subdir1/subdir2/file.type")
==> "type"

(make-pathname :name "file" :type "type" :directory '(:relative "subdir1" "subdir2"))
==> #P"subdir1/subdir2/file.type"
Run Code Online (Sandbox Code Playgroud)

特别是,directory路径名的组件表示为列表,因此,您可以使用完整的列表处理函数集directory从其他函数派生值:

(make-pathname :directory (append '(:absolute "usr" "share") '("more" "stuff"))
               :name "packages" :type "lisp")
Run Code Online (Sandbox Code Playgroud)