所以,我在SML中编写了这个quicksort函数来利用高阶函数折叠,但是它在无限循环中被挂起,而且我无法确定导致它的错误逻辑。关于在哪里看的任何建议?
(* takes in a list of numbers and an arbitrary binary relation function f *)
fun quicksort nil f = []
| quicksort [x] f = [x]
| quicksort list f =
let
(* simply choose pivot as first item in the list *)
val pivot = hd list
(* lists iterated by folding for numbers pertaining to the relation f
or its converse *)
fun test a = List.foldr (fn (x,y) => if f (pivot, x) then x::y else y) [] a
fun testC a = List.foldr (fn (x,y) => if f (pivot, x) then y else x::y) [] a
in
(* my notion is the function is looping here, since the functions test
and testC work fine on their own *)
quicksort (test list) op f @ [pivot] @ quicksort (testC list) op f
end;
感谢您的任何建议。
答案 0 :(得分:1)
问题是您调用quicksort
的子列表可以与初始列表一样长。您必须确保pivot元素不在这些列表中。
最简单的方法是使用匹配将传入列表拆分为pivot
和剩余元素列表,然后将 列表传递给测试函数。