added comment & got rid of match%pcre

This commit is contained in:
ryan committed 2023-09-30 23:20:47 -07:00
1 parent 1fdb1ebc36
commit 3d2a2f2c4d
1 file changed
+13 -12
+13 -12
View File
@@ -1,5 +1,6 @@
open Containers open Containers
(* could have simplified this a lot by getting rid of File *)
type node = type node =
| File of | File of
{ name : string { name : string
@@ -23,17 +24,13 @@ let get_dir_tree () =
match node with match node with
| File _ -> failwith "current directory cannot be a file" | File _ -> failwith "current directory cannot be a file"
| Dir dir -> | Dir dir ->
(match%pcre line with (match String.split ~by:" " line with
| {|\$ ls|} -> node | [ "$"; "ls" ] -> node
| {|dir (?<name>.*)|} -> | [ "dir"; name ] ->
let new_dir = Dir { name; parent = Some (Dir dir); children = [] } in let new_dir = Dir { name; parent = Some (Dir dir); children = [] } in
dir.children <- new_dir :: dir.children; dir.children <- new_dir :: dir.children;
node node
| {|(?<size>\d+) (?<name>.*)|} -> | [ "$"; "cd"; ".." ] ->
let new_file = File { name; size = int_of_string size } in
dir.children <- new_file :: dir.children;
node
| {|cd \.\.|} ->
(match dir.parent with (match dir.parent with
| Some parent -> parent | Some parent -> parent
| _ -> | _ ->
@@ -42,13 +39,17 @@ let get_dir_tree () =
"ERROR:%d: cant cd .. because node '%s' has no parent" "ERROR:%d: cant cd .. because node '%s' has no parent"
!line_num !line_num
dir.name) dir.name)
| {|cd (?<name>.*)|} -> | [ "$"; "cd"; name ] ->
dir.children dir.children
|> List.find (fun child -> |> List.find (fun child ->
match child with match child with
| Dir child_dir -> String.Infix.(name = child_dir.name) | Dir child_dir -> String.Infix.(name = child_dir.name)
| _ -> false) | _ -> false)
| line -> failwith @@ Printf.sprintf "failed to parse line '%s'" line)) | [ size; name ] ->
let new_file = File { name; size = int_of_string size } in
dir.children <- new_file :: dir.children;
node
| _ -> failwith @@ Printf.sprintf "failed to parse line '%s'" line))
tree tree
in in
tree tree
@@ -87,8 +88,8 @@ let part2 () =
() ()
in in
let used_space = get_node_size collect_dir_sizes tree in let used_space = get_node_size collect_dir_sizes tree in
let total_space = 70000000 in let total_space = 70_000_000 in
let required_space = 30000000 in let required_space = 30_000_000 in
let free_space = total_space - used_space in let free_space = total_space - used_space in
match match
!dir_sizes !dir_sizes