我正在做作业,而且我被困在某事上。
> data Channel a = Chan { cap :: Int
> , queue :: [a] }
> data FiniteChan a = IORef (Channel a)
> newFiniteChan :: Int -> IO (FiniteChan a)
> newFiniteChan capacity = do x <- newIORef (Chan {cap = capacity, queue = []})
> return x
基本上,我想在调用newFiniteChan时创建对Channel a
的引用,我希望FiniteChan a
表示该引用(我不能更改newFiniteChan的签名)。当我编译它时,我收到以下错误:
final.lhs:235:38:
Couldn't match expected type `FiniteChan a'
with actual type `IORef (Channel a0)'
In the first argument of `return', namely `x'
In a stmt of a 'do' block: return x
In the expression:
do { x <- newIORef (Chan {cap = capacity, queue = []});
return x }
我花了很多时间搞清楚问题,但我找不到。我感谢任何帮助。
答案 0 :(得分:1)
您必须将构造函数添加到 FiniteChan 数据类型,或将其转换为 type 别名指令,这将编译:
import Data.IORef
data Channel a = Chan { cap :: Int
, queue :: [a] }
data FiniteChan a = FiniteChan (IORef (Channel a))
newFiniteChan :: Int -> IO (FiniteChan a)
newFiniteChan capacity = do
x <- newIORef (Chan {cap = capacity, queue = []})
return $ FiniteChan x