Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data type field name from module I defined is "not in scope"

I have a Haskell file called Types.hs that contains this definition, among others:

module Types
( KnapsackItem
) where

data KnapsackItem = KnapsackItem {
weight :: Int,
cost :: Int
} deriving (Show, Eq)

Then there’s my Main.hs (also shortened here for simplicity):

import Types

evalTotal :: [KnapsackItem] -> [KnapsackItem] -> (Int, Int, String)
evalTotal items sub = (sum $ map weight sub, sum $ map cost sub, outputString)
    where outputString = "[" ++ unwords [if item `elem` sub then "1" else "0" | item 
    <- items] ++ "]"

main :: IO ()
main = do
    let items = [KnapsackItem {...}, KnapsackItem{...}, ...] -- details omitted in this example
    print $ map (evalTotal items) (subsequences items)

I get the following errors:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

src/Main.hs:67:34: Not in scope: `weight'
src/Main.hs:67:56:
    Not in scope: `cost'
    Perhaps you meant one of these:
      `const' (imported from Prelude), `cos' (imported from Prelude),
      `cosh' (imported from Prelude)

As you can see, it won’t let me access the attributes of each KnapsackItem. However, it works if I move the data definition into Main.hs and avoid the import. What am I doing wrong, please?

>Solution :

Change the export list at the beginning of Types.hs to:

module Types
    ( KnapsackItem (..)
    ) where

That will make the module export all constructors and fields of KnapsackItem. Without the (..), only the name of the type is exported.

For some extra commentary on (..) and related matters, see also What do bracketed double dots mean in Haskell?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading