Use of fold instead of custom recursion
authorUmmon <greg.burri@gmail.com>
Mon, 11 Dec 2017 08:02:45 +0000 (09:02 +0100)
committerUmmon <greg.burri@gmail.com>
Mon, 11 Dec 2017 08:02:45 +0000 (09:02 +0100)
AdventOfCode2017/Day11.fs

index 420f9a5..71e9934 100644 (file)
@@ -7,16 +7,18 @@ let distanceInHex (moves : string list) =
         let x, y = abs x, abs y
         if y >= x then y + (x - y) / 2 else x
 
-    let rec next (x, y) furthest (moves : string list) =
-        let furthest' = distance (x, y) |> max furthest
-        match moves with
-        | "n"  :: xs -> next (x, y + 2) furthest' xs
-        | "ne" :: xs -> next (x + 1, y + 1) furthest' xs
-        | "se" :: xs -> next (x + 1, y - 1) furthest' xs
-        | "s"  :: xs -> next (x, y - 2) furthest' xs
-        | "sw" :: xs -> next (x - 1, y - 1) furthest' xs
-        | "nw" :: xs -> next (x - 1, y + 1) furthest' xs
-        | _ -> (x, y), furthest'
-
-    let destination, furthest = next (0, 0) 0 moves
+    let destination, furthest =
+        moves
+        |> List.fold (
+            fun ((x, y), furthest) m ->
+                let pos =
+                    match m with
+                    | "n"  -> (x    , y + 2)
+                    | "ne" -> (x + 1, y + 1)
+                    | "se" -> (x + 1, y - 1)
+                    | "s"  -> (x    , y - 2)
+                    | "sw" -> (x - 1, y - 1)
+                    |  _   -> (x - 1, y + 1)
+                pos, distance pos |> max furthest
+            ) ((0, 0), 0)
     distance destination, furthest
\ No newline at end of file