我在学习Haskell时遇到类型问题。我有一个类型类称为Stack
,显然应该表现得像一个堆栈。我有一个Elem
简单地是Int或Bool的类型。
现在,我希望我的函数采用Stack
ofElem
并对其进行一些操作。结果实际上并不重要,但是我什至无法获取堆栈的第一个元素,而且现在也无法在数小时内找出问题所在。
import Control.Monad
data Elem = Number Int | Truth Bool deriving Eq
instance Show Elem where
show (Number i) = show i
show (Truth b) = show b
class Stack stack where
push :: a -> stack a -> stack a
top :: MonadPlus m => stack a -> m (a,stack a)
empty :: stack a
isEmpty :: stack a -> Bool
instance Stack [] where
push a stack = a:stack
top stack = if isEmpty stack then mzero else return (head stack, tail stack)
empty = []
isEmpty stack = if null stack then True else False
step :: Stack stack => String -> stack Elem -> Maybe (stack Elem)
step ex st = let e1 = top st :: Maybe (Elem, stack Elem)
--a1 = fmap fst e1
--e2 = top (fmap snd e1)
--a2 = fmap fst e2
in Nothing
我得到的错误是
Playground.hs:22:27:
Could not deduce (stack ~ stack2)
from the context (Stack stack)
bound by the type signature for
step :: Stack stack => String -> stack Elem -> Maybe (stack Ele
m)
at Playground.hs:21:9-65
`stack' is a rigid type variable bound by
the type signature for
step :: Stack stack => String -> stack Elem -> Maybe (stack Elem
)
at Playground.hs:21:9
`stack2' is a rigid type variable bound by
an expression type signature: Maybe (Elem, stack2 Elem)
at Playground.hs:22:23
Expected type: stack2 Elem
Actual type: stack Elem
Relevant bindings include
st :: stack Elem
(bound at Playground.hs:22:9)
step :: String -> stack Elem -> Maybe (stack Elem)
(bound at Playground.hs:22:1)
In the first argument of `top', namely `st'
In the expression: top st :: Maybe (Elem, stack Elem)
我真的不明白为什么Haskell拒绝此操作(甚至拒绝简单地调用top st
我的函数而无需我尝试指定类型)。
我希望有人能对此有所启发!
正如两个评论者所建议的,您需要-XScopedTypeVariables
。
以下代码为我编译:
{-# LANGUAGE ScopedTypeVariables #-}
module Foo where
import Control.Monad
data Elem = Number Int | Truth Bool deriving Eq
instance Show Elem where
show (Number i) = show i
show (Truth b) = show b
class Stack stack where
push :: a -> stack a -> stack a
top :: MonadPlus m => stack a -> m (a,stack a)
empty :: stack a
isEmpty :: stack a -> Bool
instance Stack [] where
push a stack = a:stack
top stack = if isEmpty stack then mzero else return (head stack, tail stack)
empty = []
isEmpty stack = if null stack then True else False
step :: forall stack . Stack stack => String -> stack Elem -> Maybe (stack Elem)
step ex st = let e1 = top st :: Maybe (Elem, stack Elem)
--a1 = fmap fst e1
--e2 = top (fmap snd e1)
--a2 = fmap fst e2
in Nothing
我不确定您对“无法使用forall
语法”的含义,但是如果您真的想避免使用它,也可以这样写step
:
step :: Stack stack => String -> stack Elem -> Maybe (stack Elem)
step ex (st :: stack Elem) = let e1 = top st :: Maybe (Elem, stack Elem)
--a1 = fmap fst e1
--e2 = top (fmap snd e1)
--a2 = fmap fst e2
in Nothing
您仍然需要ScopedTypeVariables
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句