【问题标题】:OCaml merge sort functionOCaml 归并排序函数
【发布时间】:2013-11-16 07:56:44
【问题描述】:

所以这是我在 OCaml 中使用的合并排序功能。有趣的是代码提供了我所期望的,这意味着它对列表进行了排序。但随后引发了一些错误。那么有人可以检查我的代码并告诉我发生了什么以及为什么会出现这些错误吗?以及如何消除它们?我是 OCaml 新手,但我真的很想知道发生了什么:

(* Merge Sort *)
(* This works but produces some extra error. Consult someone!! *)
let rec length_inner l n =
    match l with
    [] -> n
    | h::t -> length_inner t (n + 1)
;;

let length l = length_inner l 0;;

let rec take n l =
    if n = 0 then [] else
        match l with
        h::t -> h :: take (n - 1) t
;;

let rec drop n l =
    if n = 0 then l else
        match l with
        h::t -> drop (n - 1) t
;;

let rec merge x y =
    match x, y with 
    [], l -> l
    | l, [] -> l
    | hx::tx, hy::ty -> 
        if hx < hy
            then hx  :: merge tx (hy :: ty)
    else hy :: merge (hx :: tx) ty
;;

let rec msort l =
    match l with
    [] -> []
    | [x] -> [x]
    | _ ->
        let left = take (length l/2) l in 
        let right = drop (length l/2) l in
        merge (msort left) (msort right)
;;

msort [53; 9; 2; 6; 19];; 

在终端中,我得到:

        OCaml version 4.00.1

# #use "prac.ml";;
val length_inner : 'a list -> int -> int = <fun>
val length : 'a list -> int = <fun>
File "prac.ml", line 13, characters 2-44:
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
[]
val take : int -> 'a list -> 'a list = <fun>
File "prac.ml", line 19, characters 2-39:
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
[]
val drop : int -> 'a list -> 'a list = <fun>
val merge : 'a list -> 'a list -> 'a list = <fun>
val msort : 'a list -> 'a list = <fun>
- : int list = [2; 6; 9; 19; 53]
# 

【问题讨论】:

    标签: sorting functional-programming ocaml


    【解决方案1】:

    编译器告诉您,您的模式匹配并不详尽。事实上,它准确地说明了要尝试查看问题的内容。例如,您可以尝试:

    drop 2 []
    

    要解决此问题,您需要决定如何处理函数中的空列表。这是具有详尽匹配的 drop 的定义:

    let rec drop n l =
        if n = 0 then l
        else
            match l with
            | [] -> []
            | h::t -> drop (n - 1) t
    

    如果不清楚:您的代码没有说明如何处理空列表。如果列表的格式为 h :: t,您的匹配项只会说明该怎么做。但是空列表没有这种形式。您需要在匹配项中添加 [] 的案例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多