day-01-01.sml 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. (* open IntInf; *)
  2. fun read file =
  3. let
  4. val inStream = TextIO.openIn file
  5. in
  6. (* TextIO.inputAll returns a TextIO.vector, which is a string. *)
  7. TextIO.inputAll inStream
  8. end;
  9. fun count_increases [] = 0
  10. | count_increases [n] = 0
  11. | count_increases measurements =
  12. let
  13. val (first_measurement::rest_measurements) = measurements;
  14. fun iter (remaining, previous, accumulated) =
  15. if List.null remaining
  16. then
  17. accumulated
  18. else
  19. let
  20. val (current::rest) = remaining;
  21. in
  22. if current > previous
  23. then
  24. let
  25. val _ = print ((Int.toString current) ^ " > " ^ (Int.toString previous) ^ "\n");
  26. in
  27. iter (rest, current, accumulated + 1)
  28. end
  29. else
  30. iter (rest, current, accumulated)
  31. end
  32. in
  33. iter (rest_measurements, first_measurement, 0)
  34. end;
  35. val str = read "input";
  36. val lines = String.tokens (fn c => c = #"\n") str;
  37. val measurements = map (fn num_as_str =>
  38. case Int.fromString num_as_str of
  39. SOME number => number
  40. | NONE =>
  41. raise Fail "encountered a non-int string")
  42. lines;
  43. count_increases measurements;