Saturday, July 17, 2010

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 -> 0

Pattern 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