[RESOLVED] Why would adding a signature cause an error?

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?

As the error says, Map isn’t in scope. You need Map.Map (and to add Map to the qualified import from Data.Map.Strict). I’m not sure why HLS shows the type signature unqualified though. That’s strange.

1 Like

Ohhhh ok I think I understand now. I imported the functions from Data.Map.Strict but didn’t also import the Map type. Thanks – this simply did not occur to me.

HLS never qualifies types in popups (at least not in VS Code). But when adding it as signature with a code action, it is correctly qualified.

1 Like