Tail-recursive merge sort in OCaml

后端 未结 2 1333
离开以前
离开以前 2021-02-15 13:50

I’m trying to implement a tail-recursive list-sorting function in OCaml, and I’ve come up with the following code:

let tailrec_merge_sort l =
  let split l = 
           


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-15 14:04

    The expression

    merge (sort left) (sort right)
    

    is not tail-recursive; it calls both (sort left) and (sort right) recursively while there is remaining work in the call (merge).

    I think you can fix it with an extra continuation parameter:

      let rec sort l k =
        match l with
        | [] -> k [] 
        | [a] -> k [a] 
        | list -> let left, right = split list in sort left (fun leftR -> sort right (fun rightR -> k (merge leftR rightR)))
      in sort l (fun x -> x)
    

提交回复
热议问题