我可以将元组列表转换为记录列表吗?

时间:2013-12-03 17:42:43

标签: f#

我有以下代码:

open System
type Span = Span of TimeSpan with
  static member (+) (d:DateTime, Span wrapper) = d + wrapper //this is defining the + operator
  static member Zero = Span(new TimeSpan(0L))
let a = DateTime.Parse("01/12/2013")
let b = DateTime.Parse("03/12/2013")
let ts = TimeSpan.FromDays(1.0)
[a .. Span(ts) .. b] |> List.map(fun x -> x, x.DayOfYear);;

它返回一个元组列表:

  

val it:(System.DateTime * int)list = [(01/12/2013 00:00:00,335);   (02/12/2013 00:00:00,336); (03/12/2013 00:00:00,337)]

我还有一个记录类型定义为

type DateInfo = {DateandTime System.DateTime; dayOfYear int

我想将我的元组列表转换为DateInfo列表。这可能吗?

P.S。我在this thread上有很多以前的帮助,其中有人提供了有关记录的有用链接,但是我无法弄清楚如何做我需要的东西,所以我想在这里开始一个新线程更好。

1 个答案:

答案 0 :(得分:3)

您不应该将元组列表转换为记录,而是立即创建记录:

[a .. Span(ts) .. b] |> List.map(fun x -> { DateandTime =x; dayOfYear =x.DayOfYear);;

使用生成器的(+)运算符看起来有点笨拙,您可能想要阅读Seq.unfold

open System

type DateInfo = {
    DateandTime: System.DateTime
    dayOfYear: int
}

// be aware of different DateTime formats! your code breaks on different culterinfos..         
let a = new DateTime(2013, 12, 1);
let b = new DateTime(2013, 12, 3);

// Seq.unfold     
Seq.unfold (fun d -> if d < b then Some(d, d.AddDays(1.0)) else None) a
|> Seq.map (fun x -> { DateandTime=x; dayOfYear=x.DayOfYear})
|> Seq.toList // this is optional, you could use the Seq straight away as well