Advent of Haskell: Day 1

I recently completed Advent of Code 2017, and enjoyed it so much I'm going to go back to do the previous years.

I ended up doing almost all of this year's in Python as that's my most comfortable language for hacking things out, so I didn't really use this year's challenge as optimally as I could for learning. I've never done Haskell in anger so right now I'm reading Learn You A Haskell for Great Good! and I'll be completing the 2015 Advent Of Code as Haskell practice. I probably won't do it daily but I hope to complete it before too long.

For Day 1, the challenge is to count the number of open parentheses, recording the final total and also at which index we first have a negative number of open parenthesis. My haskell code is:

import Data.List
import Data.Maybe

main = interact day1

day1 :: String -> String
day1 input =
    let movement = map (\x -> if x == '(' then 1 else if x == ')' then -1 else 0) input
        positions = scanl1 (+) movement
        part1 = last positions
        part2 = (fromJust $ elemIndex (-1) positions) + 1
        unlines $ ["Part 1: " ++ (show part1), "Part 2: " ++ (show part2)]

As I'm very very new to Haskell, I'm sure what I'm writing won't be idiomatic. Please do let me know where I could improve.

All Advent Of Code challenges for the last 3 years are now available, that's 75 days of challenges, some with two challenges per day. You should join in!.

Show Comments

Get the latest posts delivered right to your inbox.