{-# Language QuasiQuotes #-}
{-|
Module      : Main
Description : Day 1 solution
Copyright   : (c) Eric Mertens, 2021
License     : ISC
Maintainer  : emertens@gmail.com

<https://adventofcode.com/2015/day/1>

Count open and closing parentheses.

>>> :main + "(())\n"
0

>>> :main + "()()\n"
0

>>> :main + "(((\n"
3

>>> :main + "(()(()(\n"
3

>>> :main + "))(((((\n"
3
1

>>> :main + "())\n"
-1
3

>>> :main + "))(\n"
-1
1

>>> :main + ")))\n"
-3
1

>>> :main + ")())())\n"
-3
1

>>> :main + "()())\n"
-1
5

-}
module Main where

import Advent (format, partialSums)
import Data.Foldable (traverse_)
import Data.List (elemIndex)

-- | >>> :main
-- 138
-- 1771
main :: IO ()
IO ()
main =
 do [Char]
inp <- [format|2015 1 %s%n|]
    let xs :: [Int]
xs = (Char -> Int) -> [Char] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Char -> Int
interpret [Char]
inp
    Int -> IO ()
forall a. Show a => a -> IO ()
print ([Int] -> Int
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Int]
xs)
    (Int -> IO ()) -> Maybe Int -> IO ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ Int -> IO ()
forall a. Show a => a -> IO ()
print ([Int] -> Maybe Int
part2 [Int]
xs)

interpret :: Char -> Int
interpret :: Char -> Int
interpret Char
'(' = Int
1
interpret Char
')' = -Int
1
interpret Char
x   = [Char] -> Int
forall a. HasCallStack => [Char] -> a
error ([Char]
"No interpretation for: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char
x])

part2 :: [Int] -> Maybe Int
part2 :: [Int] -> Maybe Int
part2 = Int -> [Int] -> Maybe Int
forall a. Eq a => a -> [a] -> Maybe Int
elemIndex (-Int
1) ([Int] -> Maybe Int) -> ([Int] -> [Int]) -> [Int] -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Int] -> [Int]
forall a. Num a => [a] -> [a]
partialSums