【问题标题】:Infinite loop in Bubblesort implementation冒泡排序实现中的无限循环
【发布时间】:2019-03-04 19:12:10
【问题描述】:

我正在尝试使用“let in end”在 SML 中创建递归冒泡排序以包含辅助函数。

当谈到为什么它不会打印任何东西时,我很迷茫。

main.sml:

val master = [1,2,3,1,4,2,8,3,2,1]: int list;

fun bubblesort ( x : int list) : int list = 
    let
        fun sort [] = []
          | sort [a] = [a]
          | sort (a::b::c) = if (a < b) then [a]@sort(b::c) else [b]@sort(a::c)

        fun issorted [] = true  
          | issorted [x] = true 
          | issorted (x::y::t) = x <= y andalso issorted(y::t)
    in
        sort x;
        if issorted x then x else bubblesort x;
        x
    end;

val result = bubblesort master

结果:

新泽西州标准 ML v110.78 [构建时间:2017 年 8 月 31 日星期四 03:45:42]
val master = [1,2,3,1,4,2,8,3,2,1]:int 列表
val bubblesort = fn :int list -> int list
=

【问题讨论】:

    标签: sml


    【解决方案1】:

    问题是你在思考,好像sort x 改变了x。在您当前的代码中,它是原始的、未排序的x,用于以if issorted x ... 开头的行中。如果 x 未排序,那么您将永远在该原始值上调用 bubblesort。事实上,由于该代码试图返回 x 本身(通过在 in 块的最后一行使用 x),即使 x 已排序,您将永远以相同的值调用 bubblesort .相反,您需要在比较中使用 sort x,最好先在 val 绑定中捕获它,然后返回 if 的值,而不是 x 本身.以下作品:

    fun bubblesort ( x : int list) : int list = 
    
        let
            fun sort [] = []
                    |sort [a] = [a]
                    |sort(a::b::c) = if (a < b) then a::sort(b::c) else b::sort(a::c);
    
            fun issorted [] = true  
              | issorted [x] = true 
              | issorted (x::y::t) = x <= y andalso issorted(y::t);
    
            val y = sort x;
        in
           if issorted y then y else bubblesort y
        end;
    

    然后:

    - bubblesort master;
    val it = [1,1,1,2,2,2,3,3,4,8] : int list
    

    请注意,我将 [a]@sort(b::c) 替换为更惯用的 a::sort(b::c)

    【讨论】:

      猜你喜欢
      • 2012-09-17
      • 1970-01-01
      • 2018-05-05
      • 2017-06-29
      • 2016-08-31
      • 1970-01-01
      • 2017-03-11
      • 2012-07-23
      相关资源
      最近更新 更多