表示文件/文件夹结构的最佳方式

时间:2015-05-14 15:24:17

标签: data-structures ocaml

我想表示一个文件结构,以便以后将其写入磁盘。我需要的是有一种方法来表示文件,文件夹,它们的关系和它们的内容。例如,表示如下文件结构:

|-one.txt -> contains "This is file 1"
|-aFolder
| |-aNestedFolder
| | |-aDoublyNestedEmptyFolder
|-anotherFolder
| |-aNestedFile -> contains "Contents of aNestedFile"
|-yetAnotherEmptyFolder

我现在正在使用它:

type fileTree =
  | File of (string * string)
  | Folder of (string * (fileTree list))

let example = [
  File ("one.txt", "This is file 1");
  Folder ("aFolder", 
      [Folder ("aNestedFolder", 
          [Folder ("aDoublyNestedEmptyFolder", [])])]) ;
  Folder ("anotherFolder", 
      [File ("aNestedFile", "Contents of aNestedFile")]);
  Folder ("yetAnotherEmptyFolder", []);
]

现在可以使用,但我想知道是否有更智能的方式来表示这样的文件结构。

1 个答案:

答案 0 :(得分:3)

您的陈述非常简单,因此除非您有更具体的要求,否则很难想出更好的陈述。

使用一个微小的(或多或少化妆品)变化:

type fileTree =
  | File of string * string
  | Folder of string * fileTree list

这不是同一类型,当您不需要直接表示对时,它会更有效。

如果你想在这种结构中快速查看文件,如果结构变得非常大,你可能想要使用嵌套的地图或哈希表。

<强>更新

对这两种类型之间的区别进行了一些讨论。在此之前已经对SO进行了很好的解释,但我还没能找到该页面。这是一个显示差异的会话:

$ ocaml
        OCaml version 4.02.1

# type f = A of (int * int);;
type f = A of (int * int)
# type g = B of int * int;;
type g = B of int * int
# let x = (8, 7);;
val x : int * int = (8, 7)
# A x;;
- : f = A (8, 7)
# B x;;
Error: The constructor B expects 2 argument(s),
       but is applied here to 1 argument(s)
# 

A构造函数接受一个值,一对int。 B构造函数采用两个单独的int值,而不是一对。

在内存中,类型f的值将包含标题和一个字段。一个字段将指向一对(标题和两个字段)。类型g的值只有一个标题和两个字段。

这不是什么大不了的事,大部分时间都很有趣(至少对我而言)。

更新2

这是对此问题的一个很好的讨论:

  

int * int vs (int * int) in OCaml sum type

相关问题