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:
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?