F# Syntax You Didn’t Know (Maybe)

by kiteason26. February 2014 11:09

Everyone plateaus a bit when learning a new language.  It’s important to guard against that and keep learning!  To that end here are six F# tricks which - maybe - you haven’t come across yet.  Enjoy.

1) Strings are sequences

Because they implement IEnumable, strings are sequences.  Which means that you don’t have to ‘manually’ pull out individual elements and process them ‘char by agonizing char’.

val ToMorse : s:string -> string

> ToMorse "ABACAB";;

val it : string = ".- -... .- -.-. .- -... "


2) You don’t always need to say (fun x -> …)

If the arguments of the function you want to call in something like a Seq.map or Seq.iter operation are the same types and order as those required by the higher-order-function in question, you don’t need to map the arguments across with the (fun x -> …) syntax.

It’s probably clearer with some examples:

3) You can pattern match in for-loop arguments

This is a naughty one!  If you use the syntax

for <Discriminated Union Pattern> in <Sequence of Discriminated Unions> do

...then the body of the loop will iterate only for those sequence items which match the DU Pattern.  This is so naughty that you’ll get a compiler warning and Jon Harrop will tell you off, but still…

4) You can pattern match on many bizarre combinations of list items

5) You can do comprehensions of floating point numbers

This is another one that is not without its risks but… you can increment values in a list or array comprehension by things other than integers.

val xValues : float [] = [|0.0; 0.1; 0.2; 0.3...

6) Active patterns can use active patterns

val PrimaryColorWays : (RainbowColor * RainbowColor * RainbowColor) [] =

[|(Red, Orange, Yellow); (Violet, Green, Orange); (Violet, Orange, Red)|]

OK, so who can shoehorn every single one of these into one application?


Add comment

  Country flag

  • Comment
  • Preview

About the author

F# bore

Month List

Page List