In F#, can a match expression 'fall through' another match? like in C# or C++?

Viewed 689

in C++ you can go a switch / case construct and omit the break in a case statement to have the execution fall though the next case.

in C#, this is done with goto case.

Can this be done in F#?

A C# example to illustrate:

switch (a)
case "a":
    ...
    break;
case "b":
    ...
    goto case "a"
case "c":
    ...

I would imagine something like:

match x with
| "a" -> ...
| "b" -> ...  + goto "a"

a practical example would be a case where:

  • "a" does some operation
  • "b" resets a counter and then does the same operation as "a"

and you'd want to avoid code duplication, but also to put the code in an external function.

2 Answers

F# is an expression based language, therefore it doesn't have imperative features like goto. However, you can still express the same logic. First of all, you can combine 'cases':

let test str =
   match str with
   | (null|"") -> printf "empty"
   | str -> printf "String: [%s]" str

And of course if you want to reuse just a part of some case logic, you can extract that in a local function:

let test str =
   let onEmpty() = printf "empty!!!"
   match str with
   | null ->
       onEmpty()
       printf "null!"
   | "" -> onEmpty()
   | str -> printf "String [%s]" str
let aFun() = ...
let bFun() = ...
let abFun() = aFun >> bFun

or like this, which one is better for your situation

let abFun() = 
     aFun() |> ignore
     bFun()

F# constrains you to do things more functional. goto is imperative operator

match x with
| "a" -> aFun()
| "b" -> abFun()
Related