Skip to content

Instantly share code, notes, and snippets.

@b0urb4k1
Last active July 6, 2017 06:47
Show Gist options
  • Save b0urb4k1/65c6f2ac686998722b7fdd98e5083424 to your computer and use it in GitHub Desktop.
Save b0urb4k1/65c6f2ac686998722b7fdd98e5083424 to your computer and use it in GitHub Desktop.
type Directory =
| Directory of string * string list * Directory list
let getFiles (Directory _, files, _) =
files
let getDirectories (Directory _, _, directories) =
directories
let rec private _pathToTree (path : string) =
let split = path.Split ([|'/'|], 2)
let headSplit = Array.head split
let splitRest = Array.get split 1
let pathDepth = path.Split '/' |> Array.length
if pathDepth = 2
then Directory (headSplit, [splitRest], [])
else Directory (headSplit, [], [_pathToTree splitRest])
let pathToTree path =
_pathToTree (sprintf "root/%s" path)
let dot =
Directory ("root", ["."], [])
let rec merge
(Directory (directoryName1, files1, subdirectories1))
(Directory (directoryName2, files2, subdirectories2))
: Directory option =
if directoryName1 = directoryName2
then
let intersect d1 d2 =
List.collect
(fun (Directory (name1, _, _) as directory1) ->
List.choose
(fun (Directory (name2, _, _) as directory2) ->
if name1 = name2
then Some (directory1, directory2)
else None
)
d2
)
d1
let intersection =
intersect subdirectories1 subdirectories2
let complement =
match intersection with
| [] -> List.append subdirectories1 subdirectories2
| _ ->
List.collect
(fun ((Directory (name1, _, _)), (Directory (name2, _, _))) ->
List.choose
(fun (Directory (name3, _, _) as directory) ->
if name1 = name3 || name2 = name3
then None
else Some directory
)
(List.append subdirectories1 subdirectories2)
)
intersection
let mergedIntersections =
List.choose
(fun (d1, d2) -> merge d1 d2)
intersection
Directory
( directoryName1
, List.append files1 files2 |> List.distinct
, List.append complement mergedIntersections
)
|> Some
else None
let p1 = "foo.xxx"
let p2 = "foo/bar.xxx"
let p3 = "foo/baz.xxx"
let path1 = pathToTree p1
let path2 = pathToTree p2
let path3 = pathToTree p3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment