Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a data type in Haskell

I'm trying to import a data type from one file to another.

Here's the module:

-- datatype.hs
module DataType (Placeholder) where

data Placeholder a = Foo a | Bar | Baz deriving (Show)

Here's the file consuming the module

-- execution.hs
import DataType (Placeholder)

main = do
    print Bar

When I run runhaskell execution.hs I get

execution.hs:4:10: Not in scope: data constructor ‘Bar’

There may be multiple problems with my code, so what is the best way to structure this so that I'm importing a specific data type from a module and able to view it?

like image 919
Mark Karavan Avatar asked Dec 18 '22 21:12

Mark Karavan


1 Answers

You have to import/export class and constructors:

In your case, PlaceHolder is the class, and Foo and Bar are the constructors.

Therefore, you should write:

-- datatype.hs
module DataType (PlaceHolder (Foo, Bar, Baz)) where

-- execution.hs
import DataType (PlaceHolder (Foo, Bar, Baz))

Or simpler:

-- datatype.hs
module DataType (PlaceHolder (..)) where

-- execution.hs
import DataType (PlaceHolder (..))

If you don’t specify what you export:

-- datatype.hs
module DataType where

Everything will be exported (classes, constructors, functions…).

If you don’t specify what you import

-- execution.hs
import DataType

everything that DataType exports will be available.

It’s generally a good practice to specify imports and exports.

like image 200
zigazou Avatar answered Jan 04 '23 14:01

zigazou