A simple F# ternary operator

A simple F# ternary operator

While porting some C# to F# recently I got sick of rewriting ternary operators like this

var result = condition ? "True Branch" : "False Branch";

into a form like this

let result = if condition then "True Branch" else "False Branch"


let result = match condition with true -> "True Branch" | false -> "False Branch"

Thankfully, although F# lacks an inbuilt ternary operator it does allow you to define your own operators

/// Custom ternary operator
let (?) truth trueBranch falseBranch =
    if truth then trueBranch else falseBranch
let test condition =
        "True branch"
        "False branch"

Share Tweet Send
You've successfully subscribed to SimonReynolds.ie
Great! Next, complete checkout for full access to SimonReynolds.ie
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.