F# break from while loop

后端 未结 7 2082
甜味超标
甜味超标 2021-02-18 14:30

There is any way to do it like C/C#?

For example (C# style)

for (int i = 0; i < 100; i++)
{
   if (I == 66)
       break;
} 
7条回答
  •  遥遥无期
    2021-02-18 15:18

    The short answer is no. You would generally use some higher-order function to express the same functionality. There is a number of functions that let you do this, corresponding to different patterns (so if you describe what exactly you need, someone might give you a better answer).

    For example, tryFind function returns the first value from a sequence for which a given predicate returns true, which lets you write something like this:

    seq { 0 .. 100 } |> Seq.tryFind (fun i ->
      printfn "%d" i
      i=66)
    

    In practice, this is the best way to go if you are expressing some high-level logic and there is a corresponding function. If you really need to express something like break, you can use a recursive function:

    let rec loop n = 
      if n < 66 then 
        printfn "%d" n
        loop (n + 1)
    
    loop 0      
    

    A more exotic option (that is not as efficient, but may be nice for DSLs) is that you can define a computation expression that lets you write break and continue. Here is an example, but as I said, this is not as efficient.

提交回复
热议问题