【问题标题】:Quick Sort Error using SML使用 SML 的快速排序错误
【发布时间】:2017-03-27 18:34:11
【问题描述】:

我上周学习了 SML,所以我尝试编写 Quicksort 代码以很好地理解它。 我的代码是:

fun quicksort(l: int list) =
    if length l < 2
    then l
    else let fun split(l:int list, v: int) =
        if null l
        then ([], [])
        else if v > hd l
        then ((hd l)::(#1 split(tl l, v)), #2 split(tl l, v))
        else (#1 split(tl l, v), (hd l)::(#2 split(tl l, v)))
    in
        (#1 split(quicksort(tl l), hd l)) @ ((hd l)::(#2 split(quicksort(tl l), hd l)))
    end

这是错误信息:

Standard ML of New Jersey v110.75 [built: Sat Sep 29 12:51:13 2012]
- stdIn:21.18-21.35 Error: operator and operand don't agree [type mismatch]
  operator domain: {1:'Y; 'Z}
  operand:         int list * int -> 'X
  in expression:
    (fn {1=1,...} => 1) split
stdIn:21.8-21.56 Error: operator and operand don't agree [type mismatch]
  operator domain: {2:'Y; 'Z}
  operand:         int list * int -> 'X
  in expression:
    (fn {2=2,...} => 2) split
stdIn:22.8-22.56 Error: operator and operand don't agree [type mismatch]
  operator domain: {1:'Y; 'Z}
  operand:         int list * int -> 'X
  in expression:
    (fn {1=1,...} => 1) split
stdIn:22.37-22.54 Error: operator and operand don't agree [type mismatch]
  operator domain: {2:'Y; 'Z}
  operand:         int list * int -> 'X
  in expression:
    (fn {2=2,...} => 2) split
stdIn:24.4-24.35 Error: operator and operand don't agree [type mismatch]
  operator domain: {1:'Y; 'Z}
  operand:         int list * int -> int list * _ list
  in expression:
    (fn {1=1,...} => 1) split
stdIn:24.49-24.80 Error: operator and operand don't agree [type mismatch]
  operator domain: {2:'Y; 'Z}
  operand:         int list * int -> int list * _ list
  in expression:
    (fn {2=2,...} => 2) split
-

我将给定列表的头部设置为枢轴,并将列表拆分为 int 列表对并再次合并。

我认为不存在类型匹配问题,但我不知道为什么它不起作用。 请给我一些帮助:(

【问题讨论】:

    标签: sorting sml


    【解决方案1】:

    Moscow ML 中运行您的代码以突出显示问题代码:

    ! Toplevel input:
    !         then ((hd l)::(#1 split(tl l, v)), #2 split(tl l, v))
    !                           ^^^^^
    ! Type clash: expression of type
    !   int list * int -> int list * 'a list
    ! cannot have type
    !   {1 : 'b, ...}
    

    此类型错误表明使用 int list × int -> int list × 'a list 类型的表达式,而代码的另一部分期望它是 {1 类型:'b,...}。第一种类型是函数,最后一种类型是包含至少一个条目的记录。

    问题在于#1 split(tl l, v) 被解释为(#1 split)(tl l, v),而不是如您所愿的#1 (split (tl l, v))。也就是说,您需要函数的 result 的第一个记录条目,而不是函数本身的;这是无意义的。虽然#1 实际上是一个宏而不是一个函数,但它在语法上的行为就像一个函数,应该这样组合。

    由于您在 SML 中进行 QuickSort,您可能会对问题 True QuickSort in Standard ML 感兴趣,其中包含 1) RosettaCode 的版本,它使用模式匹配,而不是像 hdtl 这样会导致您崩溃的可怕部分函数程序在运行时出现意外,以及 2) John Coleman 的 QuickSort 版本,它实际上是算法上的 QuickSort。 :-P

    【讨论】:

    • 非常感谢!我真的很想投票给你的答案,但我不能因为我的名声:(
    • @Rexion:不客气。既然您提出了问题,您可以将答案标记为“已接受”。
    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 2021-10-01
    • 1970-01-01
    • 2013-08-09
    • 2021-09-21
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    相关资源
    最近更新 更多