Context
- I’m working on Day 3 of Advent of Code 2022
- I use functions from the
Data.Map
library
Code
module Main where
import qualified Data.Map.Strict as Map (fromList, lookup)
import qualified Data.Set as Set (fromList, toList)
import Data.List (sort)
import Data.Maybe (fromMaybe)
type Compartment1 = String
type Compartment2 = String
type CommonItem = Char
main :: IO ()
main = do
raw <- readFile "./data/day_03.txt"
let parsed = lines raw :: [String]
lookupList = Map.fromList $ zip ['a'..'z'] [1..] ++ zip ['A'..'Z'] [27..]
commonItems = map (itemInCommon . divideAndDistinct) parsed :: [CommonItem]
commonItemPriorities = map (getPriority lookupList) commonItems :: [Maybe Integer]
-- Solve part 1 (7428)
print . sum $ map (fromMaybe 0) commonItemPriorities
divideAndDistinct :: String -> (Compartment1, Compartment2)
divideAndDistinct items = (
sort . distinct $ take compartmentSize items,
sort . distinct $ drop compartmentSize items
)
where
compartmentSize :: Int
compartmentSize = round $ (fromIntegral $ length items :: Double) / 2
distinct :: String -> String
distinct = Set.toList . Set.fromList
itemInCommon :: (Compartment1, Compartment2) -> CommonItem
itemInCommon (comp1, comp2) = head . map fst . filter snd $ map (itemTest comp2) comp1
where
itemTest :: Compartment2 -> Char -> (Char, Bool)
itemTest comp2 x = (x, x `elem` comp2)
getPriority lookupList commonItem = Map.lookup commonItem lookupList
Issue
This concerns the value lookupList
and the function getPriority
. lookupList
has the type listed by HLS in the screenshot.
Cabal will compile and build without issue.
However, the moment I add the signature from HLS to the code, it gets marked as an error. Cabal will not built this.
The same issue is observed in getPriority
.
Questions
- What is the reason for this behaviour?
- How can I avoid this in future?