F# generate a sequence/array of dates

后端 未结 2 1879
我寻月下人不归
我寻月下人不归 2021-02-08 22:55

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(\"         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-08 23:08

    There are two problems - firstly you need to specify the interval you want to use between elements of the list. This would be a TimeSpan, however it does not have a static Zero member.

    This constraint is required by the skip range operator which requires the 'step' type to have static (+) and Zero members

    You can define your own structure which supports the required operations however:

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

    You can then do:

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

    Edit: Here's an alternative syntax using discriminated unions 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]
    

提交回复
热议问题