Question

I want to implement am Abstract Datype in haskell. Given a moule with a defined type, say Mytype:

module A (myType,MyType) where

type MyType = Float

mytype :: Float -> MyType
myType f = f

Implemented internally as a single Float, I exported only a function to construct a value given a Float, and the type itself. The problem is, when I load that module, I can acces the implementation.

Given:

module B where
import A

data OtherType = One MyType
               | Two MyType MyType
               deriving Show

I can construct an object of type OtherType like this:

One $ mytype 1.0

Or like this:

One $ (1.0 :: Float)

With a real abstraction I shouldn't be able to do that!

How can I export the type Mytype, in a way such that I can only construct values from my constructor functions

Was it helpful?

Solution

You can create an Algebraic Datatype instead:

module A (myType,MyType) where

data MyType = MyType Float

mytype :: Float -> MyType
myType f = MyType f

Then, trying to evaluate things like

One (MyType 3.0)

throws "Not in scope: data constructor `MyType'"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top