Home > Software design >  Stacks in Haskell
Stacks in Haskell

Time:10-02

I am not sure how to use newtype states in Haskell: So I tried to create a stack that has two states: Active and Inactive, when the stack is active you can do operations on it, when it is Inactive any operations that are done on the stack are automatically ignored. I tried implementing it like:

newtype State a = myState [a]
data myState = Active | Inactive

Where State a is a myState with a list of items with type of a. But it does not seem to be the correct way to define this? It gives me the following error:

Not a data constructor: ‘myState’

How would I implement this properly?

CodePudding user response:

A data constructor and type constructor can not have a name that starts with a lowercase, you can define one with:

data State a = State MyState [a]
data MyState = Active | Inactive

CodePudding user response:

You'll want to use either

data Stack a = Stack StackState [a]
data StackState = Active | Inactive

or

data Stack a = ActiveStack [a] | InactiveStack [a]

The Stack/ActiveStack/InactiveStack are the constructors for values of the Stack a type. Their names, as well as the type names, must be capitalised.

  • Related