ocaml - Best way to represent a file/folder structure -
i want represent file structure later write disk. need have way represent files, folders, relationships , contents. example, represent file structure this:
|-one.txt -> contains "this file 1" |-afolder | |-anestedfolder | | |-adoublynestedemptyfolder |-anotherfolder | |-anestedfile -> contains "contents of anestedfile" |-yetanotheremptyfolder
i using right now:
type filetree = | file of (string * string) | folder of (string * (filetree list)) let example = [ file ("one.txt", "this file 1"); folder ("afolder", [folder ("anestedfolder", [folder ("adoublynestedemptyfolder", [])])]) ; folder ("anotherfolder", [file ("anestedfile", "contents of anestedfile")]); folder ("yetanotheremptyfolder", []); ]
this works now, i'd know if there's smarter way represent file structure this.
your representation straightforward, it's hard think of better 1 unless have more specific requirements.
a tiny (more or less cosmetic) change use:
type filetree = | file of string * string | folder of string * filetree list
this isn't same type, , tiny bit more effective when don't need direct representation of pairs.
if want files in kind of structure, , if structure going large, might want use nested maps or hashtables.
update
there's discussion of difference between 2 types. has been explained before here @ so, haven't been able find page. here's session showing difference:
$ ocaml ocaml version 4.02.1 # type f = of (int * int);; type f = 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) # x;; - : f = (8, 7) # b x;; error: constructor b expects 2 argument(s), applied here 1 argument(s) #
the a
constructor takes 1 value, pair of ints. b
constructor takes 2 separate int values, not pair.
in memory, value of type f
have header , 1 field. 1 field point pair (a header , 2 fields). value of type g
have header , 2 fields.
it's not big deal, it's interesting (at least me).
update 2
here's discussion of issue:
Comments
Post a Comment