【发布时间】:2010-03-27 14:17:13
【问题描述】:
我正在尝试在 OCaml 中实现一个尾递归列表排序功能,我想出了以下代码:
let tailrec_merge_sort l =
let split l =
let rec _split source left right =
match source with
| [] -> (left, right)
| head :: tail -> _split tail right (head :: left)
in _split l [] []
in
let merge l1 l2 =
let rec _merge l1 l2 result =
match l1, l2 with
| [], [] -> result
| [], h :: t | h :: t, [] -> _merge [] t (h :: result)
| h1 :: t1, h2 :: t2 ->
if h1 < h2 then _merge t1 l2 (h1 :: result)
else _merge l1 t2 (h2 :: result)
in List.rev (_merge l1 l2 [])
in
let rec sort = function
| [] -> []
| [a] -> [a]
| list -> let left, right = split list in merge (sort left) (sort right)
in sort l
;;
但它似乎实际上并不是尾递归,因为我遇到了“评估期间堆栈溢出(循环递归?)”错误。
您能帮我找出这段代码中的非尾递归调用吗?我已经搜索了很多,没有找到它。是不是 sort 函数中的 let 绑定?
【问题讨论】:
标签: sorting ocaml tail-recursion