Adventures in F# - Part 2

fsharp, development comments edit

Yesterday I started devoting 2 pomodoros a day on learning F#. I will post my findings as I go along. Currently I’m on my second day and still working TryFSharp.org tutorial website. I think these notes will come in handy in the future so I decided to post them regularly.

What I’ve learned today

  • Record types can be defined by type keyword such as
type Book = 
  { Name: string;
    AuthorName: string;
    Rating: int;
    ISBN: string }

New objects of type Book can be created by let bindings

let expertFSharp = 
  { Name = "Expert F#";
    AuthorName = "Don Syme, Adam Granicz, Antonio Cisternino";
    Rating = 5;
    ISBN = "1590598504" }  

These values are immutable but new objects can be created based on the current values:

let partDeux = { expertFSharp with Name = "Expert F# 2.0" }

If there are similar types F# will infer the last one defined. So when there are duplicate types it may be needed to use explicit definitions. For example

let expertFSharp = 
  { Name = "Expert F#";
    AuthorName = "Don Syme, Adam Granicz, Antonio Cisternino";
    Book.Rating = 5;
    ISBN = "1590598504" }  

In the above example Rating is referred explicitly by using the dot notation so that the correct type can be resolved.

  • Option types represent data that may or may not exist. There are two types: Some and None. Some is used when the data does exist and None is used when it doesn’t.
type Book =
  { Name: string;
    AuthorName: string;
    Rating: int option;
    ISBN: string }

Now Rating value is optional can be assigned None

Rating = None;
  • Discriminated Unions are equivalent of enums in C# and they can be defined by listing pipe-separated values:
type MushroomColor =
| Red
| Green
| Purple

Basics are covered in 4 sections in TryFSharp.org and this concludes the notes for the basics section. Next section is called Advanced F# Programming is composed of 5 sections. Tomorrow in my alloted time I’ll be looking into these sections.

Resources

Comments