【发布时间】:2017-02-08 06:35:50
【问题描述】:
我正在处理一个额外的任务,其中 SML 中快速排序的分区函数只能使用 foldr 完成,并且不能使用库函数。我已经很好地完成了分区,并且快速排序的基础知识也很好,但是我遇到了问题,它似乎将错误的列表合并在一起/以错误的顺序合并。
(*comp is a placeholder, I will be given a comparator function and list as input*)
fun comp a b = a > b;
(*Both partition functions are working as intended.*)
fun getGreater (a::b) c = foldr (fn (a, lst) => if (comp a c) then a::lst else lst) [] (a::b);
fun getLesserOrEqual (a::b) c = foldr (fn (a, lst) => if not (comp a c) then a::lst else lst) [] (a::b);
fun merge (a::b) (c::d) = foldr (op::) (c::d) (a::b);
fun tripleMerge (a::b) c (d::e) = merge (a::b) (c::(d::e));
(*Removes head, uses head as pivot. Recursive calls on results on getLesserOrEqual and getGreater*)
fun sort [] = [] | sort (a::b) = if ([a] = (a::b)) then [a] else
tripleMerge (sort(getLesserOrEqual b a)) a (sort(getGreater b a));
例如,以下是我正在运行的一些测试。当我在纸上遵循我的逻辑时,我得到的答案与不正确的项目不同:
sort [2, 6, 3, 6, 4, 100, 0];
val it = [0,2,3,6,4,6,100] : int list (*Incorrect*)
sort [1, 2, 3, 4, 5];
val it = [1,2,3,4,5] : int list
sort [5, 4, 3, 2, 1];
val it = [5,4,3,2,1] : int list (*incorrect*)
sort [1, 100, 10, 1000, 0];
val it = [0,1,10,100,1000] : int list
sort [1, 2, 1, 2, 1, 2, 5, 1];
val it = [1,1,1,1,2,2,2,5] : int list
我的错误对任何人来说都是显而易见的吗?
【问题讨论】:
-
使用您显示的代码,当我运行
sort [2, 6, 3, 6, 4, 100, 0];时,我收到错误消息uncaught exception Match [nonexhaustive match failure],而不是错误排序的列表。您确定您发布的代码正确吗?