Browse Source

Use the Jane Street libraries instead

Getty Ritter 3 years ago
parent
commit
5566210fd6
2 changed files with 18 additions and 21 deletions
  1. 1 1
      01/dune
  2. 17 20
      01/main.ml

+ 1 - 1
01/dune

@@ -1,4 +1,4 @@
 ;; This declares the hello_world executable implemented by hello_world.ml
 (executable
  (name main)
- (libraries base))
+ (libraries base stdio))

+ 17 - 20
01/main.ml

@@ -1,4 +1,6 @@
-let sample_list = [
+open Base
+
+let sample_list : int list = [
     1721;
     979;
     366;
@@ -7,42 +9,37 @@ let sample_list = [
     1456;
 ]
 
-let load_list filename =
-  let lines = ref [] in
-  let f = open_in filename in
-  try
-    while true
-    do
-      lines := int_of_string (input_line f) :: !lines
-    done; !lines
-  with End_of_file ->
-        close_in f;
-        List.rev !lines
-
+(* load the provided filename *)
+let load_list (filename : string) : int list =
+  let open Stdio.In_channel in
+  let lines = with_file ~f:input_lines filename
+  in List.map ~f:Int.of_string lines
 
-let (>>=) list fn = let _ = List.map fn list in None
+(* You might notice that this isn't actually >>=: I just wanted to
+   have a non-parenthesized foreach! *)
+let (>>=) list fn = let _ = List.map ~f:fn list in None
 
 let part_one source =
   let res = Base.With_return.with_return (fun r ->
     source >>= fun a ->
     source >>= fun b ->
-      if a != b && a + b == 2020 then r.return (Some (a, b))
+      if a <> b && a + b = 2020 then r.return (Some (a, b))
     ) in
   match res with
-  | None -> Printf.printf "Unable to find result\n"
-  | Some (x, y) -> Printf.printf "Got (%d * %d) = %d\n" x y (x * y)
+  | None -> Stdio.printf "Unable to find result\n"
+  | Some (x, y) -> Stdio.printf "Got (%d * %d) = %d\n" x y (x * y)
 
 let part_two source =
   let res = Base.With_return.with_return (fun r ->
     source >>= fun a ->
     source >>= fun b ->
     source >>= fun c ->
-      if a != b && b != c && a != c && a + b + c == 2020 then r.return (Some (a, b, c))
+      if a <> b && b <> c && a <> c && a + b + c = 2020 then r.return (Some (a, b, c))
     ) in
   match res with
-  | None -> Printf.printf "Unable to find result\n"
+  | None -> Stdio.printf "Unable to find result\n"
   | Some (x, y, z) ->
-     Printf.printf "Got (%d * %d * %d) = %d\n" x y z (x * y * z)
+     Stdio.printf "Got (%d * %d * %d) = %d\n" x y z (x * y * z)
 
 let main() =
   let source = load_list "input" in