Why “do…while” does not exist in F#

后端 未结 8 498
-上瘾入骨i
-上瘾入骨i 2021-02-04 00:36

I cannot find \"do...while...\"

I have to code like this:

let bubbleSort a=
    let n = Array.length a
    let mutable swapped = true
    let mutable i =         


        
8条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 01:39

    Although a bit more verbose, you can use recursive functions to avoid the "do while" as in :

    let swap (a:int[]) i j =
        let t = a.[i]
        a.[i] <- a.[j]
        a.[j] <- t
    
    let rec bubbleSortAux a nMax j swapped =
      if j >= 0 && j <= nMax then
        if a.[j] > a.[j+1] then
          swap a j (j+1)
          bubbleSortAux a nMax (j+1) true
        else
          bubbleSortAux a nMax (j+1) false
      else
        swapped
    
    let rec bubbleSortLoop a nMax =
      if bubbleSortAux a nMax 0 false then
        bubbleSortLoop a (nMax - 1)
    
    let bubbleSort a =
        bubbleSortLoop a (a.Length - 2)
    

提交回复
热议问题