F# Tricks: Concise BoolToInt
As a C# programmer, you'd probably write BoolToInt as follows in F#:
let boolToInt3 b = if b = true then 1 elif b = false 0
Not a big win over C# yet, but a few things to point out about the concise syntax: Indentation implies blocks. There is no 'return' keyword. This function is statically typed, you don't see types since the compiler infers the types.
As a novice F# programmer a trick you learn is pattern matching. Pattern matching is like a case statement, but it's an expression and it's really powerful. I'll go into more details on pattern matching in future posts. For now, notice the elegance of the below:
let boolToInt2 b = match b with | true -> 1 | false -> 0Pattern matching is so useful to F# there is a syntax for creating a function of one parameter that only pattern matches, using that syntax, we define boolToInt in the final form of:
let boolToInt3 = function | true -> 1 | false -> 0
Comments
public int BoolToInt (int b){
return (b ? 1 : 0);
}
Which isn't too shabby and almost as concise if you don't mind the short hand.
In C family languages there is no expression for the switch statement. Pattern matching is really a switch expression.
Holler if you'd like to see more F# posts.