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

2020-05-22 01:23发布

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 = 0
    while swapped do
        swapped <- false
        for j = 0 to n-i-2 do
            if a.[j] > a.[j+1] then
                let t = a.[j]
                a.[j] <- a.[j+1]
                a.[j+1] <- t
                swapped <- true
        i <- i+1

The code is bad without "do...while".
Sadly, "break/continue" are also not available.

标签: f#
8条回答
Ridiculous、
2楼-- · 2020-05-22 01:59

I do not know about F# very well, but F# is a functional language. Usually, there is no such thing as "for" or "while" loops in functional programming languages.

Functional languages define functions in a mathematical sense (like f(x) => ...). Writing a program comes down to defining and combining a set of mathematical functions. This means that the only way of coding loops is using recursion.

In Mathematics, there is no way of saying:

f(x) => "do 5 times this"

What you'd do is define f like:

                 count > 0  : f(x, count-1)
f(x, count) => {
                 count <= 0 : ...

And then use this function as in:

y = f(x, 5)

This would be exactly how you implement functions in functional languages. At least, this is true for purely functional languages like Haskell...

查看更多
手持菜刀,她持情操
3楼-- · 2020-05-22 01:59

You can do something like

let mutable ind = 0
while (
    //Do your stuff here

    //Now condition part return some boolean value
    ind < 10
) do ind <- ind +1

I just recently found this way. It feels a bit hacky but what I like is that you can build something more complex what usually caused issues in C#, C++.

let mutable ind = 0
while (
    (some condition) && (
    //do something
    let someValue = Eval ....

    //Now more complex condition
    ind + someValue < 10
    )
) do ind <- ind +1
查看更多
登录 后发表回答