我已经编写了这个mergesort实现,如果我将divide函数放在mergesort函数之外,它会很好地工作。但是,当我试图将divide作为mergesort的内部函数时,我遇到了一个语法错误。
我知道,一定有一些非常简单的解释。我在网上找遍了,但什么也没找到。
let mergesort list =
let rec sort lists acc = (
let rec merge sublist1 sublist2 merged_list =
match sublist1 with
|[] -> merged_list @ sublist2
|hd1 :: tl1 ->
match sublist2 with
|[] -> merged_list @ sublist1
|hd2 :: tl2 ->
if hd1 < hd2 then merge tl1 sublist2 (merged_list @ hd1::[])
else merge sublist1 tl2 (merged_list @ hd2::[])
in match lists with
|[] ->
(match acc with
|[] -> []
|hd :: [] -> hd
|_ -> sort acc [])
|hd :: tl -> sort (List.tl tl) ((merge (List.hd tl) hd [])::acc)
)
and rec divide list list_of_lists = (
match list with
[] -> list_of_lists
|hd :: tl -> divide tl ((hd :: []) :: list_of_lists)
)
in sort (divide list []) []
;;
结果是:
Characters 567-570:
and rec divide list list_of_lists = (
^^^
Error: Syntax error