F#生成日期序列/数组 [英] F# generate a sequence/array of dates

查看:79
本文介绍了F#生成日期序列/数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在F#中,我可以轻松完成

In F# I can easily do

let a = [1 .. 10];;

那我为什么不能做

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


let dateList = [a .. b]

它给出了错误Type constraint mismatch. The type DateTime is not compatible with type TimeSpan

推荐答案

存在两个问题-首先,您需要指定列表元素之间要使用的间隔.这将是TimeSpan,但是它没有静态的Zero成员.

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.

跳过范围运算符需要此约束,要求"step"类型具有静态(+)Zero成员

您可以定义自己的结构来支持所需的操作,但是:

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) }

您可以执行以下操作:

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

这是您可能更喜欢使用区分联合的另一种语法:

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]

这篇关于F#生成日期序列/数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆