我是一名.Net开发人员,但对F#和一般的函数式编程不熟悉。有人能指出我在以下问题上的正确方向:
我正在尝试迭代我从CSV中读取的一系列数据并构建一种摘要列表。伪代码是
type record = { Name:string; Time:DateTime;}
type summary = {Name:String; Start:DateTime; End:DateTime}
示例数据: (姓名时间)
我正在尝试迭代序列并构建第二个序列:
Seq<Summary>
(姓名开始结束)
我应该将seq<record>
传递给以foreach
样式迭代的函数,还是有更好的方法呢?我已经在F#中对数据进行了排序,因此数据按时间顺序排列。我不必担心它们会出现故障。
如果是C#,我可能会做(伪代码):
List<Summary> summaryData
foreach(var r in records)
{
Summary last = summaryData.LastOrDefault()
if(last == null)
{
summaryData.add( new Summary from r)
}
else
{
if(last.Name = r.Name)
{
last.End = r.Time
}
else
{
summaryData.add( new Summary from r)
}
}
任何帮助都非常感谢!
答案 0 :(得分:4)
函数式编程是(以及其他好东西)声明式的。 您的问题可以表述为:按字符串对字符串和时间进行分组,然后为每组最小时间和最长时间检索。
可以转换为F#:
sequenceOfRecords
|> Seq.groupBy (fun r -> r.Name)
|> Seq.map (fun (name, records) ->
let times = Seq.map snd records
{ Name = name; Start = Seq.min times; End = Seq.max times })
如果你想要,你也可以返回(名字,分钟,最大)元组。
答案 1 :(得分:4)
除了声明性之外,函数式编程还包含抽象具体类型的基本要求的能力,即泛型编程。只要符合要求(F#称为约束),您的算法就会以一般方式适用,而与具体数据结构无关。
如问题描述中所述,您可能拥有任何可以从中提取密钥的序列(对象的有序集合的最常用数据结构)。应对这些密钥进行不等式测试,因此存在等式约束。依赖序列的顺序,任何事物都是不受约束的。代表为F#签名,您的输入数据由source:seq<'T>
描述,关键投影函数为projection:('T -> 'Key) when 'Key : equality
。
作为完整的功能签名,我想建议projection:('T -> 'Key) -> source:seq<'T> -> seq<'T * 'T> when 'Key : equality
。返回一对序列可避免引入其他类型参数。它匹配输入,除了一些选择性重新排列。这是该功能的可能实现,没有效率或甚至正确性的要求。请注意,'Key
上的等式约束是推断的,从未明确说明。
let whenKeyChanges (projection : 'T -> 'Key) (source : seq<'T>) =
// Wrap in option to mark start and end of sequence
// and compute value of every key once
seq{ yield None
yield! Seq.map (fun x -> Some(x, projection x)) source
yield None }
// Create tuples of adjacent elements in order to
// test their keys for inequality
|> Seq.pairwise
// Project to singleton in case of the first and the
// last element of the sequence, or to a two-element
// sequence if keys are not equal; concatenate the
// results to obtain a flat sequence again
|> Seq.collect (function
| None, Some x | Some x, None -> [x]
| Some(_, kx as x), Some(_, ky as y)
when kx <> ky -> [x; y]
| _ -> [] )
// Create tuples of adjacent elements a second time.
|> Seq.pairwise
// Only the first and then every other pair will contain
// indentical keys
|> Seq.choose (fun ((x, kx), (y, ky)) ->
if kx = ky then Some(x, y) else None )
在具体(X * string) list
上的示例应用程序,密钥为X.当seq<record>
提取密钥时,它在(fun r -> r.Name)
上同样有效。
type X = A | B | C
[ A, "10:01"
A, "10:02"
A, "10:03"
B, "11:15"
B, "11:25"
B, "11:30"
C, "12:00"
A, "13:01"
A, "13:05" ] |> whenKeyChanges fst
// val it : seq<(X * string) * (X * string)> =
// seq
// [((A, "10:01"), (A, "10:03")); ((B, "11:15"), (B, "11:30"));
// ((C, "12:00"), (C, "12:00")); ((A, "13:01"), (A, "13:05"))]
答案 2 :(得分:2)
对于这种问题,你必须迭代一个集合保持一些状态,而迭代通常的方法将是使用折叠或递归。但是,我倾向于在这里展开。
open System
type Record = { Name : string; Time : DateTime }
type Summary = { Name : String; Start : DateTime; End : DateTime }
let records = [ { Name = "A"; Time = DateTime(2015, 7, 24, 10, 1, 0) }
{ Name = "A"; Time = DateTime(2015, 7, 24, 10, 2, 0) }
{ Name = "A"; Time = DateTime(2015, 7, 24, 10, 3, 0) }
{ Name = "B"; Time = DateTime(2015, 7, 24, 11, 15, 0) }
{ Name = "B"; Time = DateTime(2015, 7, 24, 11, 25, 0) }
{ Name = "B"; Time = DateTime(2015, 7, 24, 11, 30, 0) }
{ Name = "C"; Time = DateTime(2015, 7, 24, 12, 0, 0) }
{ Name = "A"; Time = DateTime(2015, 7, 24, 13, 1, 0) }
{ Name = "A"; Time = DateTime(2015, 7, 24, 13, 5, 0) } ]
let createSummary records =
let times = records |> Seq.map (fun r -> r.Time)
{ Name = (Seq.head records).Name
Start = Seq.min times
End = Seq.max times }
let summarize records =
records
|> Seq.unfold (fun (restOfRecords : seq<Record>) ->
if Seq.isEmpty restOfRecords then None
else
let firstRecord = Seq.head restOfRecords
let belongsToSameGroup (r : Record) = firstRecord.Name = r.Name
let thisGroup = restOfRecords |> Seq.takeWhile belongsToSameGroup
let newRest = restOfRecords |> Seq.skipWhile belongsToSameGroup
Some (createSummary thisGroup, newRest) )
summarize records
|> Seq.iter (fun s -> printfn "Name: %s, Start: %s, End: %s" s.Name (s.Start.ToString()) (s.End.ToString()))