标准ml值限制错误

时间:2011-02-27 16:01:54

标签: functional-programming sml smlnj

我需要帮助理解为什么我在此代码中遇到值限制错误以及如果可能的话我如何解决它。

特别是在val cnil中,我试图创建一个空的CLIST结构来匹配签名,但我不断得到这个值限制错误。

感谢您的帮助

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 *)
  val cnil =
    let
      val reqCh = channel()
      val replyCh = channel()
      fun loop l = case recv reqCh of
          CONS x =>
            (loop (x::l))
        | 
          HEAD => (let fun head (h::t) = h | head [] = Empty in send(replyCh, head(l)) end ; loop l)
    in
      spawn(fn () => loop nil);
      CLIST {reqCh = channel(), replyCh = channel() }
    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:10.7-22.5 Warning: type vars not generalized because of
   value restriction are instantiated to dummy types (X1,X2,...)
clist.sml:1.1-29.4 Error: value type in structure doesn't match signature spec
    name: cnil
  spec:   'a ?.Clist.clist
  actual: ?.X1 ?.Clist.clist

1 个答案:

答案 0 :(得分:1)

您的代码存在两个问题。一个是值限制错误,您可以通过更改

来解决
val cnil : 'a clist

val cnil : unit -> 'a clist

val cnil =

fun cnil () =

第二个问题是cnil似乎没有做任何事情 - 也许是因为head函数返回Empty而不是提升Empty而你是多余的? Basis Library中已经有一个hd函数可以执行此操作。 clist类型也不需要是数据类型。我想你想要的是:

structure Clist : CLIST =
struct
  open CML

  datatype 'a request = CONS of 'a | HEAD

  type 'a clist = { reqCh : 'a request chan, replyCh : 'a chan }

  (* create a clist *)
  fun cnil () =
    let
      val clist as {reqCh, replyCh} = {reqCh = channel(), replyCh = channel()}       
      fun loop l = case recv reqCh of
          CONS x =>     
            (loop (x::l))
        |                                     
          HEAD => (send(replyCh, hd l); loop l)
    in                        
      spawn(fn () => loop nil);
      clist
    end


  fun cons x (clist as {reqCh, replyCh})=
    (send (reqCh, CONS x); clist)

  fun hd (CLIST {reqCh, replyCh}) = (send (reqCh, HEAD); recv replyCh)
end