我正在尝试使用标准 ML 的 CML 扩展来实现并发列表,但我遇到了错误,这可能与我是标准 ML 的新手有关。我已将 clist 实现为具有输入和输出 channel ,并将列表状态存储在循环中。但是我的代码无法编译并给出以下错误
structure Clist : CLIST =
struct
open CML
datatype 'a request = CONS of 'a | HEAD
datatype 'a clist = CLIST of { reqCh : 'a request chan, replyCh : 'a chan }
(* create a clist with initial contents l *)
val cnil =
let
val req = channel()
val reply = channel()
fun loop l = case recv req of
CONS x =>
(loop (x::l))
|
HEAD => (send(reply, l); loop l)
in
spawn(fn () => loop nil);
CLIST {reqCh=req,replyCh=reply}
end
fun cons x (CLIST {reqCh, replyCh})=
(send (reqCh, CONS x); CLIST {reqCh = reqCh, replyCh = replyCh})
fun hd (CLIST {reqCh, replyCh}) = (send (reqCh, HEAD); recv replyCh)
end
这是签名文件
signature CLIST =
sig
type 'a clist
val cnil : 'a clist
val cons : 'a -> 'a clist -> 'a clist
val hd : 'a clist -> 'a
end
我遇到的错误:
clist.sml:21.4-21.35 Error: operator and operand don't agree [circularity]
operator domain: {replyCh:'Z list chan, reqCh:'Z list request chan}
operand: {replyCh:'Z list chan, reqCh:'Z request chan}
in expression:
CLIST {reqCh=req,replyCh=reply}
最佳答案
所以你的问题在于你对clist
的定义
datatype 'a clist = CLIST of { reqCh : 'a request chan, replyCh : 'a chan }
这表示请求 channel 接收 'a
请求并回复 'a
。这与您的实现不一致。当您在 channel 上发送 CONS x
请求时,您是在说将 'a
类型的 x
添加到列表中,但是当您发送HEAD
请求,你是说把整个列表还给我。因此,CONS
请求应采用 'a
,而 HEAD
请求应返回 'a 列表
。您可以通过将 clist
定义更改为
datatype 'a clist = CLIST of { reqCh : 'a request chan, replyCh : 'a list chan }
我还建议将 cnil
的定义更改为 unit -> 'a clist
函数,这样您就可以创建不同的并发列表。
例如:
val l1 = Clist.cnil()
val l2 = Clist.cnil() (*cons'ing onto l2 won't affect l1*)
关于concurrency - 标准 ML/CML 错误运算符 - 操作数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5117646/