Sml Bubblesort实现中的无限循环

Sml Bubblesort实现中的无限循环,sml,Sml,我试图在SML中创建一个递归冒泡排序,使用“let-in-end”来包含帮助函数 当谈到为什么它什么都不打印时,我很困惑 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)

我试图在SML中创建一个递归冒泡排序,使用“let-in-end”来包含帮助函数

当谈到为什么它什么都不打印时,我很困惑

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
val master=[1,2,3,1,4,2,8,3,2,1]:int list;
有趣的泡泡运动(x:int-list):int-list=
让
有趣的排序[]=[]
|排序[a]=[a]
|排序(a::b::c)=如果(a问题在于,您的思维是强制性的,好像
排序x
变异x一样。在当前代码中,它是原始的、未排序的
x
,如果是排序的x…
,则在
开头的行中使用。如果该
x
未排序,则您将永远对该原始值调用
bubblesort
。事实上,由于该代码试图返回
x
本身(通过将
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;
请注意,我将
[a]@sort(b::c)
替换为更具idomatic的
a::sort(b::c)

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