首先,当列表非常随机时,排序不起作用,例如f [2,3,4,1,2,4,6,0,6,7]
其次,回答您关于此特定功能如何工作的问题,
您可以通过在代码中添加以下 print 来轻松地对其进行可视化:
fun f ([x]) = [x]
| f(x :: ls) = (print( (Int.toString (x)) ^ "\n");
let
val (y :: ys) = f ls
val x_str = Int.toString (x)
val y_str = Int.toString (y)
val ys_str = concat (map Int.toString ys);
val y_gt_x = if y > x then " ---> this one applies " else ""
val x_gt_y = if x >= y then " ---> this one applies " else ""
in
(print ("if " ^ y_str ^ " > " ^ x_str ^
"\n then " ^ x_str ^ " :: " ^ y_str ^ ys_str ^ y_gt_x ^
"\n else " ^ y_str ^ " :: " ^ x_str ^ ys_str ^ x_gt_y ^ "\n");
if y > x then x :: y :: ys
else
y :: x :: ys)
end)
上面的随机列表输出如下:
- f [2,3,4,1,2,4,6,0,6,7];
2
3
4
1
2
4
6
0
6
if 7 > 6
then 6 :: 7 ---> this one applies
else 7 :: 6
if 6 > 0
then 0 :: 67 ---> this one applies
else 6 :: 07
if 0 > 6
then 6 :: 067
else 0 :: 667 ---> this one applies
if 0 > 4
then 4 :: 0667
else 0 :: 4667 ---> this one applies
if 0 > 2
then 2 :: 04667
else 0 :: 24667 ---> this one applies
if 0 > 1
then 1 :: 024667
else 0 :: 124667 ---> this one applies
if 0 > 4
then 4 :: 0124667
else 0 :: 4124667 ---> this one applies
if 0 > 3
then 3 :: 04124667
else 0 :: 34124667 ---> this one applies
if 0 > 2
then 2 :: 034124667
else 0 :: 234124667 ---> this one applies
val it = [0,2,3,4,1,2,4,6,6,7] : int list
-
如您所见,函数f 在let 绑定部分递归调用自身。 (检查代码:
let
val (y :: ys) = f ls
如您所见,f ls 是函数 f 的递归调用,因此您对 y :: ys 是 in 主体内的递归调用的分析是不正确的,因为这只是在元素y 到列表ys)
in 正文不会被评估,除非一直位于列表末尾。因此in 正文将首先评估列表的最后两个元素,例如7 > 6 并相应地增加列表 ys。
第三,回答第一点为什么排序功能f不能正常工作是因为它不断向ys添加新元素,而没有查看新元素是否在ys中按顺序放置关于其余元素。是的,列表ys 的第一个元素与要添加的新元素进行比较,因此两者中最大的元素将首先添加到ys 的其余部分,但这并不能保证正确的位置到ys的第二个和第三个等元素。