【问题标题】:SML Unbound value identifier Error in Insert Function插入函数中的 SML 未绑定值标识符错误
【发布时间】:2018-08-13 06:59:24
【问题描述】:

我的单独功能有问题。单独返回一个列表,该列表在列表 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]。每当我对其进行任何测试时,都会出现错误:

! Unbound value identifier: separate 

这是我正在使用的代码:

 (*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));  

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

【问题讨论】:

  • 您的separate 定义格式不正确,因此您在测试之前遇到了语法错误。
  • 如果你反转列表,从反转列表的头部插入,然后反转结果,这会简单得多。
  • 我很困惑如何反转列表会使函数变得不那么复杂。
  • 在列表的“头端”工作要容易得多。

标签: sml ml mosml


【解决方案1】:

您的 separate 看起来像是两个不同定义的合并 - 第一个是没有定义的非柯里化版本,然后是一个有定义的柯里化版本。

你可能是说

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

但是通过列表向后工作会使事情变得相当复杂。
从头到尾工作要容易得多,并且在处理前后反转列表。
然后,您需要的“全部”是一个助手,它在列表中的每个 k:th 位置插入一个元素。
可能是这样的:

(*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

【讨论】:

  • 感谢您解决了我的问题!
猜你喜欢
  • 1970-01-01
  • 2021-04-12
  • 2019-05-13
  • 1970-01-01
  • 1970-01-01
  • 2012-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多