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 

Comments

Jake said…
As a C# programmer, I may actually just do it like this:

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.
Anonymous said…
Well said Jake - ? is the conditional operator, which is 'abnormal' in C languages because it lets you do control flow in an expression as opposed to a statement (aka you can assign it to a variable).

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.

Popular posts from this blog

Finding CLR exceptions without visual studio

Why do I keep getting exception code e0434352?

Powershell script to enable windows to capture localhost traffic in wireshark