Search code examples
f#semantics

if requires an else clause


I have essentially the following code in a function, and I would like to eliminate the duplication of doSomethingElse():

fun a ->
    if a = b then
        let c = expensiveOperation()
        if c = d then
            result
        else
            doSomethingElse()
    else
        doSomethingElse()

I think I should be able to eliminate both else clauses. and let it return either result or doSomethingElse(). When I do that, the error message from the compiler is: "This expression was expected to have type unit but here has type int "

Why does the if expression require the else clause?


Solution

  • This is equivalent to what you wrote, but I wonder if you mean something else.

    if a = b && expensiveOperation() = d then result
    else doSomethingElse()