Haskell 无法识别类型

Haskell not recognizing the type

我有这个自定义类型

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

当我想做这样的事情时

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)

我明白了

    * 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)

我的问题是,为什么这是一个错误,因为计算机堆栈可以是 Stack.Stack 值

您的 valueInt,因此 push 不能将其推送到 Stack (Either Address Value)?要求item的类型和stack的items相同

您可以使用 Right 将其转换为 Either a Value 并将其压入堆栈,因此:

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

一个Either a b并不意味着它可以是a类型或b类型。它是一种具有两个类型构造函数 LeftRight 的类型。 Either a b 的元素因此是 Left aRight b,但不是 ab 直接。