DEV Community

Discussion on: Advent of Code #1 (in JavaScript & Haskell)

Collapse
 
kirkcodes profile image
Kirk Shillingford • Edited

Nice solve. I did a similar method to your js version, but in F#. Haskell definitely has some more elegant options though. F# isn't lazy, so all the solutions I thought of where I made pairs or triples would have me going through the entire list multiple times. But I feel good that someone else looked at it and immediately saw the folds. Because folds are amazing. :D

// read the data in as a list of strings then convert to integers
open System.IO

let data = 
    File.ReadAllLines(@"day1part1.txt") 
    |> Array.map int
Enter fullscreen mode Exit fullscreen mode

Part one

let folder (increases, last) next =
    if next > last then increases + 1, next else increases, next

// System.Int32.MaxValue is .NET's largest int32 so the first value will always decrease

let day1part1solution =
    fst <| Array.fold folder (0, System.Int32.MaxValue) data
Enter fullscreen mode Exit fullscreen mode

Part two

let folder2 (increases, last3) (index, next) =
    // we just fill up the triple for the first 3 iterations. 
    if index < 3 then
        increases, last3 @ [next]
    else
        let next3 = List.tail last3 @ [next]
        if List.sum next3 > List.sum last3 then increases + 1, next3 else increases, next3

// we can use the indexed function to convert our list of values to (index value) pairs

let day1part2solution =
    fst <| Array.fold folder2 (0, []) (Array.indexed data)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sethcalebweeks profile image
Caleb Weeks

This looks great, thanks for sharing! F# is on my to do list of languages to dig into more. I was actually looking for the pipe operator from F# when trying to make the Haskell version, but sadly, it isn't in the prelude. It's cool that you used a fold with a tuple!