F # generate sequence / date array

In F #, I can easily do

let a = [1 .. 10];; 

Then why can't I do

 let a = DateTime.Parse("01/01/2012") let b = DateTime.Parse("01/01/2020") let dateList = [a .. b] 

It gives a Type constraint mismatch. The type DateTime is not compatible with type TimeSpan error Type constraint mismatch. The type DateTime is not compatible with type TimeSpan Type constraint mismatch. The type DateTime is not compatible with type TimeSpan

+7
source share
2 answers

There are two problems: first, you need to specify the interval that you want to use between the list items. It will be a TimeSpan , however it does not have a static member of Zero .

This restriction is required by the operator of the run operator , which requires the type "step" to have static elements (+) and Zero

You can define your own structure that supports the required operations:

 type TimeSpanW = { span : TimeSpan } with static member (+) (d:DateTime, wrapper) = d + wrapper.span static member Zero = { span = new TimeSpan(0L) } 

Then you can:

 let ts = new TimeSpan(...) let dateList = [a .. {span = ts} .. b] 

Edit: Here is an alternative syntax using discriminated associations that you may prefer:

 type Span = Span of TimeSpan with static member (+) (d:DateTime, Span wrapper) = d + wrapper static member Zero = Span(new TimeSpan(0L)) let ts = TimeSpan.FromDays(1.0) let dateList = [a .. Span(ts) .. b] 
+14
source

Here's a funky way to create a list of dates. Note. I do not take responsibility for this, as I received it from someone else.

 open System let a = new DateTime(2013,12,1) let b = new DateTime(2013,12,5) Seq.unfold (fun d -> if d < b then Some(d, d.AddDays(1.0)) else None) a |> Seq.toList;; 

It returns:

val it: DateTime list = [01/12/2013 00:00:00; 12/02/2013 00:00:00; 12/03/2013 00:00:00; 12/12/2013 00:00:00]

+11
source

All Articles