0

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

2
  • type doesn't create anything new. It just creates a convenient name for an already existing type. Once the code is compiled, your type synonyms are gone, and mytype will have type Float -> Float Commented Feb 15, 2014 at 4:50
  • type behaves equivalent to typedef in C if you're familiar with that. You're looking for data or newtype. Commented Feb 15, 2014 at 13:30

1 Answer 1

2

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'"

Sign up to request clarification or add additional context in comments.

1 Comment

Or newtype. The key point is to not use type, because that's not what it does.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.