Pat­tern match­ing is every­where in F#, you can use it in let bind­ings, in func­tion para­me­ters, in for loops, every­where, and it is totally amaz­ing. It is in my opin­ion one of the best fea­tures of F#, and in func­tional lan­guages in gen­eral, heck, Erlang goes as far as not hav­ing an assign­ment oper­a­tor and every­thing is pat­tern matched instead (yup, that’s right, ‘=’ is the pat­tern match oper­a­tor in Erlang, not assign­ment!). Once you’ve had a chance to work with it you’ll under­stand why those func­tional folks love it so much!

In terms of excep­tion han­dling, con­sider this piece of code in C#:

Notice that the switch state­ment allows you to apply the same han­dler to mul­ti­ple cases but not the catch state­ments, which leads to dupli­cated excep­tion han­dling code. Wouldn’t it be nice if you don’t have to keep repeat­ing yourself?

Now, let’s see how pat­tern match­ing in F# lets us do just that:

Pretty neat, right? Not only are you able to group han­dling code for dif­fer­ent excep­tions, you can also use wild card ( _ ) and when guards (e.g. | _ as ex when ex.Message.Contains(“Oops”) to match any excep­tion whose mes­sage con­tains the term ‘Oops’) too, which give you a very fine con­trol over which han­dler is used for what exceptions.

As the pat­terns are matched from top to bot­tom, if you move the wild­card pat­tern to the top you’ll receive a set of gen­tle warn­ings from the com­piler let­ting you know that doing so will mean that each of the sub­se­quent pat­terns will never be matched.

It’s also worth not­ing that whilst F# has try-catch and try-finally expres­sions, there is no try-catch-finally expres­sion.

Share

Ayande posted a tax cal­cu­la­tion chal­lenge the other day here, and here’s my F# solu­tion for the chal­lenge:

Enjoy!

Share

When you con­sider the age old prob­lem of rep­re­sent­ing dif­fer­ent shapes (cir­cle, tri­an­gle, square, rec­tan­gle, etc.) my OO fed devel­oper brain nat­u­rally jumps to a class hier­ar­chy along the line of:

image

This is per­fectly fine and legit, but it’s not the only way to approach things. Since I’ve been on a more var­ied diet of pro­gram­ming par­a­digms I’m much more open to the idea of using F#’s dis­crim­i­nated unions to rep­re­sent hier­ar­chi­cal data.

Dis­crim­i­nated union is a fun­da­men­tal type in func­tion pro­gram­ming, and for C# devel­op­ers, think of it as an Enum with strongly typed names where the names don’t have to be of the same type. Using dis­crim­i­nated unions, you can rewrite the above code as:

image

And to test it, let’s cre­ate some shapes and work­out their respec­tive areas:

image

Was that more dif­fi­cult than its C# coun­ter­part? Not at all, in fact, I’ve lit­tered the F# code with com­ments and still ended up with near half as much code! Check out my solu­tion for project euler prob­lem 54, a work­ing poker hand eval­u­a­tor in 100 lines of code , pretty sweetSmile

Clos­ing thoughts…

That said, class hier­ar­chies are great at mod­el­ling real world enti­ties and they allow you to cap­ture com­mon­al­i­ties and shared behav­iours, if done cor­rectly they can remove dupli­cated code and reduce defects.

Dis­crim­i­nated unions on the other hand, are a great fit for hier­ar­chi­cal data struc­tures such as binary tree, and for small hier­ar­chies it requires lit­tle over­head in set­ting them up so it can give you a nice pro­duc­tiv­ity boost.

Whilst I’m not sug­gest­ing that you should start con­vert­ing all your class hier­ar­chies to dis­crim­i­nated unions, I think there is a lot of value in hav­ing it in your tool­box nonethe­less. The more tools you have at your dis­posal the bet­ter, being able to use the right tool for the right task beats ham­mer­ing a screw in my opinion!

Share

C# devel­op­ers should be famil­iar with the yield key­word that was intro­duced in C# 2.0, and you’ll be pleased to know that F# also has the yield key­word which works in con­junc­tion with F#’s equiv­a­lent of IEnu­mer­ablesequences.

You can cre­ate sequences in F# using sequence expres­sions:

image

In addi­tion, you can also use the yield! (pro­nounced yield bang) key­word to return a sub­se­quence which is merged into the final sequence. Using a rather con­trived exam­ple (sorry…) let’s com­pare the out­put of yield and yield!:

image

Look at how the sig­na­tures dif­fer for these two sequences:

image

and how the val­ues in the two sequences dif­fer too:

image

The yield! key­word is sim­i­lar to IEnumerable.SelectMany in its abil­ity to flat­ten a col­lec­tion of col­lec­tions but it’s far more pow­er­ful as you can mix and match it with other yield/yield! state­ments and give you a level of expres­sive­ness that IEnumerable.SelectMany does not.

Share

In F#, you can defined record types which dif­fer from tuples and dis­crim­i­nated unions in that they allow you to orga­nize val­ues into a type and name those val­ues through fields:

image

Looks like a cut-down ver­sion of a stan­dard .Net class with a cou­ple of prop­er­ties? Yes they do, but records offer sev­eral advan­tages over the .Net classes.

Type Infer­ence

One of the biggest advan­tage records offer is that it works seam­lessly with F#‘s type infer­ence sys­tem. Whereas classes must be anno­tated in order to be used, record types can be inferred by the fields you access!

Con­sider this sim­ple function:

image

and see what its func­tion sig­na­ture reads:

image

Magic! Well, with a caveat :-P As you can imag­ine, if you define a sec­ond record type which con­tains the same set of fields then it might just con­fuses the com­piler a lit­tle. For instance, if you define a record type for employees:

image

The func­tion sig­na­ture for the print­Per­son func­tion will become:

image

So to tell the print­Per­son func­tion to use the Per­son record instead, you’ll need to anno­tate the para­me­ter p:

image

Immutabil­ity

Unlike classes, record fields are immutable by default. This immutabil­ity by default approach (zero side effect) is inline with every­thing else in F# and in func­tional lan­guages in gen­eral, and offers a degree of safety guarantee.

How­ever, whether immutabil­ity is an advan­tage very much depends on your use case, Eric Lip­pert made an excel­lent argu­ment here that the lack of side effects and immutable data struc­tures func­tion lan­guages offer are both advan­tages and disadvantages.

For­tu­nately, with F# record types, it’s pos­si­ble to change the field val­ues, either by using the copy and update record expres­sion:

image

or you can explic­itly spec­ify that a field should be mutable:

image

then you are allowed to update the value of the muta­ble fields:

image

No Inher­i­tance

Records can­not be inher­ited, which gives you a future guar­an­tee of safety but then again you can equally make argu­ments against it, another post another day maybe..

Pat­tern Matching

Records can be used as part of stan­dard pat­tern match­ing whereas classes can­not with­out resort­ing to active pat­terns or with when guards.

This is impor­tant, as you’re likely to be using pat­tern match­ing every­where in your code and frankly, why wouldn’t you? It’s so awe­some ;-) You can mach the struc­ture of records and not every record field needs to be a part of the pat­tern match:

image

Equally you can cap­ture val­ues and match literal:

image

Struc­tural Equal­ity Semantics

Stan­dard .Net classes have ref­er­ence equal­ity seman­tics (two ref­er­ence type vari­ables are deemed equal if they point to the same loca­tion in mem­ory), but records have struc­tural equal­ity seman­tics (two val­ues are deemed equal if their fields are equal):

image

In this respect, records are the same as .Net structs, which also struc­tural equal­ity seman­tics and can­not be inherited.

Update 27/09/2011:

One thing I for­got to men­tion is that whilst you can define a record type with just the list of fields, you can also add meth­ods and prop­er­ties using the mem­ber keyword:

image

Share