In F#, how to construct a record list with DateTime values?

Viewed 75

In F#, assume I have a person record as:

type person = 
   { LastName: string option
     BirthDate: System.DateTime option }

Now, I want to create a list of 100 persons (this fails. Both name and The System.DateTime(...) is incorrect):

let people = [for a in 1 .. 100 
                do yield {
                            LastName= Some "LastName"+a 
                            BirthDate = System.DateTime(2012,11,27)
                          }]

How is this done?

TIA

1 Answers

There are two separate issues with the code, but your general approach is good!

First, Some "LastName"+a is interpereted as (Some "LastName")+a, which is not the right parenthesization. Also a is an int which cannot be automatically turned into a string, so you need to explicitly convert it. The correct version is Some("LastName" + string a).

Second, System.DateTime(2012,11,27) is DateTime, but you need an option. You can fix this just by adding Some and the right parentheses, i.e. Some(System.DateTime(2012,11,27)).

As a bonus, you can reduce do yield to -> (this is just a syntactic sugar to make this kind of thing shorter). I would write:

open System

let people = 
  [ for a in 1 .. 100 ->
      { LastName= Some ("LastName"+string a) 
        BirthDate = Some(DateTime(2012,11,27)) } ]
Related