我在 List 上有一个非常简单的MergeSort实现。
/// Divide the list into (almost) equal halves
let rec split = function
| [] -> [], []
| [x] -> [x], []
| x1::x2::xs -> let xs1, xs2 = split xs
x1::xs1, x2::xs2
/// Merge two sorted lists
let rec merge xs ys =
match xs, ys with
| [], _ -> ys
| _, [] -> xs
| x::xs', y::ys' when x <= y -> x::merge xs' ys
| _, y::ys' -> y::merge xs ys'
let rec mergeSort = function
| [] -> []
| xs -> let xs1, xs2 = split xs
merge (mergeSort xs1) (mergeSort xs2)
但每当我尝试使用 F# Interactive 中的任何输入进行测试时:
let xs = mergeSort [1;4;3;2];;
我遇到了一个值限制错误:
错误 FS0030:值限制。值 'xs' 已被推断为具有泛型类型 val xs : '_a list when '_a : compare 将 'xs' 定义为简单的数据项,使其成为具有显式参数的函数,或者,如果您不打算这样做要通用,请添加类型注释。
为什么会这样?有什么简单的修复方法?