Glement
Glement

Reputation: 401

Haskell not recognizing the type

I have this custom types

data Stack a = Empty | a :<| (Stack a)
             deriving (Show, Read, Eq)
type Value = Int
type ComputerStack = Stack.Stack (Either Address Value)

And when i want to do something like this

push :: a -> Stack a -> Stack a
push a b = a :<| b

runS :: Value -> ComputerStack -> Seq.Seq Value
runS value stack
  | value == 0  = stack
  | otherwise = runS 0 (Stack.push value stack)

I get this

    * Couldn't match type `Int' with `Either Address Value'
      Expected type: ComputerStack
        Actual type: Stack.Stack Value
    * In the second argument of `runS', namely
        `(Stack.push value stack)'
      In the expression: runS 0 (Stack.push value stack)
      In an equation for `runS':
          runS value stack
            | value == 0 = stack
            | otherwise = runS 0 (Stack.push value stack)
   |
37 |   | otherwise = runS 0 (Stack.push value stack)

My question is, why this is an error since computer stack can be Stack.Stack Value

Upvotes: 1

Views: 79

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

Your value is an Int, hence push can not push that on a Stack (Either Address Value)? It requires that the type of the item and the items of the stack are the same.

You can use Right to convert it to an Either a Value and push that on the stack, so:

runS :: Value -> ComputerStack -> ComputerStack
runS value stack
  | value == 0  = stack
  | otherwise = Stack.push (Right value) stack

An Either a b does not mean that it can be an a type or a b type. It is a type that has two type constructors Left and Right. An element of Either a b is thus a Left a or a Right b, but not a or b directly.

Upvotes: 4

Related Questions