Using Records like Objects (F#)

Records are an F# thing. And the concept which I will set out in the example below took me a while to get my head around (the syntax). But it’s really very simple.

Records can have functions as their fields. The following example involves the use of a custom type (NamerRecord). NamerRecord is a record with 2 functions as its fields.

  1. First off, I will create/initialise a NamerRecord record with a name (line 19). At that point, neither of the record’s functions have been called.
  2. Then, I’ll call the record’s SayName function (line 22).
  3. Then I will change the name of the record (line 23),
  4. Following which, I will call the SayName function again (line 24).
open System.Drawing

// a NamerRecord record that will act as our object
type NamerRecord =
    { Rename: string -> unit;
      SayName: unit -> unit }

//  This identifier (aNameThing) has the type "string -> NamerRecord". 
//  We pass in a string and end up with a NamerRecord.
//  It's a functional programming thing. Functions can be values. 
let aNameThing initialName =    
    let currentName = ref initialName
    {   Rename = 
            fun newName -> currentName := newName;
        SayName = 
            fun() -> printf "%s\n" !currentName; }

//  This is the instantiation of our NamerRecord type
let dave = aNameThing "Bobby Sixkiller"

//  call the functions defined in the NamerRecord type
dave.SayName()
dave.Rename("Vince Black (aka Reno Raines)")
dave.SayName()

printf "\n\n"
System.Console.ReadKey() |> ignore

We’re getting object-like behaviour out of a record:

In my next post, I’ll take this a bit further to confuse you even more!

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>