【发布时间】:2014-03-15 10:44:41
【问题描述】:
我正在编写一个函数来从列表中删除具有相同值的邻居。我不明白这里的语法错误是什么。这就是我所拥有的:
let rec rem_dup_neighb l =
let rec rem_dup_neighb_aux l lastseen retl =
match l with
[]->retl
|[()]->[()]
| (y::rest) -> if(y==lastseen) then rem_dup_neighb_aux l lastseen retl else rem_dup_neighb_aux l y (y::retl)
in rem_dup_neighb_aux l 9000 [];;
函数的最后一行出现以下错误:
Error: This expression has type int but an expression was expected of type
unit
例如,如果你将 [1;2;2;3;5] 传递给函数,它应该返回 [1;2;3;5]
感谢任何帮助。谢谢
更新: 函数似乎是无限循环:
let rec rem_dup_neighb l =
let rec rem_dup_neighb_aux l lastseen retl =
match l with []->retl
| (y::rest) -> if(y==lastseen) then rem_dup_neighb_aux l lastseen retl else rem_dup_neighb_aux l y (y::retl)
in
match l with
(lastseen::rest) -> rem_dup_neighb_aux l lastseen []
更新 2: 没有减少每次迭代的问题。不过,函数现在似乎返回 [5;3;2] 而不是 [1;2;3;5]。
let rec rem_dup_neighb l =
let rec rem_dup_neighb_aux l lastseen retl =
match l with []->retl
| (y::rest) -> if(y==lastseen) then rem_dup_neighb_aux rest lastseen retl else rem_dup_neighb_aux rest y (y::retl)
in
match l with
[]->[]
|(lastseen::rest) -> rem_dup_neighb_aux l lastseen []
更新 3:
let rec rem_dup_neighb l =
let rec rem_dup_neighb_aux l lastseen retl =
match l with []->retl
| (y::rest) -> if(y==lastseen) then rem_dup_neighb_aux rest lastseen retl else rem_dup_neighb_aux rest y (y::retl)
in
match l with
[]->[]
|(lastseen::rest) -> rem_dup_neighb_aux l lastseen [lastseen]
【问题讨论】:
-
您更新的函数每次都将相同的列表传递给
rem_dup_neighb_aux的递归调用。您希望每次递归调用都沿列表进行,因此在此处传递rest。 -
您还缺少底部匹配中的空列表案例。
-
好的,谢谢。修复了无限循环。嗯,函数返回 [5;3;2] 而不是 [1;2;3;5]。我明白为什么第一个元素被删除了。还需要以某种方式反转输出。
-
List.rev应该足够了。 (累加一个列表然后在最后反转它是函数式编程中相当常见的模式。) -
不允许使用库函数:/