插入函数中的SML未绑定值标识符错误

时间:2018-03-05 15:13:33

标签: sml ml mosml

我的单独功能有问题。 Separate返回一个列表,该列表在列表l的每个k元素之后插入元素x(从中计数) 列表的结尾)。例如,单独的(1,0,[1,2,3,4])应返回[1,0,2,0,3,0,4]并分开(3,0,[1,2,3, 4])应该返回[1,0,2,3,4]。每当我对它运行任何测试时,我都会收到错误:

 (*Function returns length of lst   *)
fun length(lst: int list): int =
  case lst of
    [] => 0
  | h::t => 1 + length(t) 

(*Insert element x at the kth position in the list 
  and return the new list*)
fun kinsert [] x k = [x]
  | kinsert ls x 0 = x::ls
  | kinsert (l::ls) x k = l::(kinsert ls x (k - 1)) 

(* c: keeps track of where we are in the list 
   n: determines if we insert element at given position  
   z: holds length of the list *)
fun sep_help k x l c n z= 
  if c = z then l 
  else if n = k then (sep_help k x (kinsert l x c) (c+2) 0 z )
  else (sep_help k x l (c+2) (n+1) z) ; 

(*Returns list l with x inserted after each k element *)
fun separate (k: int, x: 'a, l: 'a list) : 'a list = 
  | separate k x l = (sep_help k x l 0 0 (length l));  

这是我使用的代码:

document.getElementById("box").style

任何人都知道可能导致错误的原因是什么?

1 个答案:

答案 0 :(得分:1)

你的separate看起来像是两个不同定义的合并 - 首先是一个没有定义的未经证实的版本,然后是一个有一个的咖喱版本。

你可能意味着

fun separate (k: int, x: 'a, l: 'a list) : 'a list = sep_help k x l 0 0 (length l);  

但是通过列表向后工作会使事情变得复杂 从头部到尾部工作要容易得多,并且在处理之前和之后反转列表 那么"所有"你需要的是一个帮助器,它在列表中的每个第k个位置插入一个元素 这样的事情,也许是:

(*Returns list l with x inserted after each k element *)
fun separate (k: int, x: 'a, l: 'a list) : 'a list = 
  let
    fun kinsert [] _ = []
      | kinsert ls 0 = x::(kinsert ls k)
      | kinsert (l::ls) i = l::(kinsert ls (i-1))
in
    List.rev (kinsert (List.rev l) k)
end