2014-02-07 282 views
0

所以,我寫了一首歌SML這個快速排序功能利用高階函數摺疊,但它在一個無限循環得到掛了,我不能牽制這是造成它在錯誤的邏輯。任何建議在哪裏看?無限循環?

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

感謝您的任何建議。

回答

1

的問題是,在其上調用quicksort子列表可以只要初始列表。你必須確保轉動部件不能在這些列表。

最簡單的方法是使用匹配將傳入列表拆分爲pivot和剩餘元素列表,然後將列表傳遞給測試函數。

+0

該訣竅;謝謝! – c0nn