fun sortAsc (l : int list) : int list = ListMergeSort.sort (op >) l fun sum (l : int list) : int = foldl (op +) 0 l fun substrToInt (substr: substring) : int = valOf (Int.fromString (Substring.string substr)) val file = TextIO.openIn "day_1.txt" val input = TextIO.inputAll file; TextIO.closeIn file; val lines = String.tokens (fn (char) => char = #"\n") input val pairs = map (fn (line) => let val substr = Substring.extract (line, 0, NONE) in [ substrToInt (Substring.takel Char.isDigit substr), substrToInt (Substring.taker Char.isDigit substr) ] end ) lines val lists = ( sortAsc (map (fn (pair) => hd pair) pairs), sortAsc (map (fn (pair) => List.last pair) pairs) ) (* Part 1 *) val distances = ListPair.map (fn (n1, n2) => abs(n1 - n2)) lists val totalDistance = sum distances (* Part 2 *) val similarities = ListPair.map (fn (n1, n2) => let val frequency = List.length (List.filter (fn (n) => n = n1) (#2 lists)) in n1 * frequency end ) lists val similarityScore = sum similarities