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

后端 未结 8 490
-上瘾入骨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:33

    It turns out to be quite easy to write a good enough do-while in F# as a higher-order function:

    let doWhile f c =
        f ()
        while c () do
            f ()
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题