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:

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


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -