-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay1Vanilla.hs
54 lines (45 loc) · 1.53 KB
/
Day1Vanilla.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
module Day1Vanilla where
import Data.Char (isDigit)
import Data.List (tails)
import qualified Data.List.NonEmpty as N
import Witherable (mapMaybe)
{- This module solves AOC 2023 Day 1 relying as much as possible on built-in types (ie, Char) and vanilla techniques.
- For a type safer solution (eg, modelling digits as ADT), that relies on parser combinators, see Day1.hs
-
- Explicit recursion is avoided, by relying on `tails` (of comonadic inspiration)
-}
program :: FilePath -> IO ()
program = (=<<) print . fmap solve . readFile
solve :: String -> (Int, Int)
solve input = (answer1, answer2)
where
answer1 = (sum . part1) input
answer2 = (sum . part2) input
part1 :: String -> [Int]
part1 =
fmap (read . firstAndLast)
. mapMaybe (N.nonEmpty . filter isDigit)
. lines
part2 :: String -> [Int]
part2 =
fmap (read . firstAndLast)
. mapMaybe (N.nonEmpty . parseAll)
. lines
firstAndLast :: N.NonEmpty a -> [a]
firstAndLast l = [N.head l, N.last l]
parse :: String -> Maybe Char
parse [] = Nothing
parse ('o' : 'n' : 'e' : _) = Just '1'
parse ('t' : 'w' : 'o' : _) = Just '2'
parse ('t' : 'h' : 'r' : 'e' : 'e' : _) = Just '3'
parse ('f' : 'o' : 'u' : 'r' : _) = Just '4'
parse ('f' : 'i' : 'v' : 'e' : _) = Just '5'
parse ('s' : 'i' : 'x' : _) = Just '6'
parse ('s' : 'e' : 'v' : 'e' : 'n' : _) = Just '7'
parse ('e' : 'i' : 'g' : 'h' : 't' : _) = Just '8'
parse ('n' : 'i' : 'n' : 'e' : _) = Just '9'
parse (c : _)
| isDigit c = Just c
| otherwise = Nothing
parseAll :: String -> String
parseAll = mapMaybe parse . tails