F# – Match Expressions

by Svetlozar Angelov 15. January 2010 10:45

I posted an article about how to get started with F# - Getting Started with F#. However if you want to use it on a daily basis it is better to get functional and if you want to get functional you have to be ok with matching expressions. The technique is awesome. And because code speaks  for itself, here is an example:

let list = [1;2;3;4;5;6;7;8;9;10]

let rec Sum list = 
    match list with 
    | [] -> 0           
    | head::tail -> head + Sum tail
    
let sum = Sum list

The Cons Pattern (head::tail) is the cool stuff here, splitting the list into first element - the rest of the list.

Things get better adding conditions to the match. Here is how we sum only the even numbers:

let list = [1;2;3;4;5;6;7;8;9;10]

let rec Sum list = 
    match list with 
    | [] -> 0           
    | head::tail when head % 2 = 0 -> head + Sum tail
    | head::tail ->Sum tail
    
let sum = Sum list

 

You can use a when clause to specify an additional condition that the variable must satisfy to match a pattern. Such a clause is referred to as a guard. The expression following the when keyword is not evaluated unless a match is made to the pattern associated with that guard.

When specifying the matches you have to be careful with their order. It is a lot like handling exceptions. When a pattern is matched the searching stops, to illustrate the problem:

let rec Sum list = 
    match list with 
    | [] -> 0           
    | head::tail ->Sum tail
    | head::tail when head % 2 = 0 -> head + Sum tail   //we will never get into this

 

So as with exceptions, put the more specific patterns above the general  patterns.

Tags:

programming

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen