与 F# 中的元组匹配的模式不完整



我定义一个点

type TimeSeriesPoint<'T> = 
    { Time : DateTimeOffset
      Value : 'T }

和一系列

type TimeSeries<'T> = TimeSeriesPoint<'T> list

我假设此列表中的点是按时间排序的。

我正在尝试压缩两个时间序列,一般来说,它们将具有相同时间的点,但其中任何一个都可能缺少一些点。

知道为什么我在下面的代码中收到不完整模式匹配的警告吗?

let zip (series1 : TimeSeries<float>) (series2 : TimeSeries<float>) =
    let rec loop revAcc ser1 ser2 =
       match ser1, ser2 with
       | [], _ | _, [] -> List.rev revAcc
       | hd1::tl1, hd2::tl2 when hd1.Time = hd2.Time ->
           loop ({ Time = hd1.Time; Value = (hd1.Value, hd2.Value) }::revAcc) tl1 tl2
       | hd1::tl1, hd2::tl2 when hd1.Time < hd2.Time ->
           loop revAcc tl1 ser2
       | hd1::tl1, hd2::tl2 when hd1.Time > hd2.Time ->
           loop revAcc ser1 tl2
    loop [] series1 series2

如果我这样写,我不会得到任何警告,但它是尾递归的吗?

let zip' (series1 : TimeSeries<float>) (series2 : TimeSeries<float>) =
    let rec loop revAcc ser1 ser2 =
       match ser1, ser2 with
       | [], _ | _, [] -> List.rev revAcc
       | hd1::tl1, hd2::tl2 ->
           if hd1.Time = hd2.Time then
               loop ({ Time = hd1.Time; Value = (hd1.Value, hd2.Value) }::revAcc) tl1 tl2
           elif hd1.Time < hd2.Time then
               loop revAcc tl1 ser2
           else 
               loop revAcc ser1 tl2
    loop [] series1 series2

一般来说,在最后一个模式中有一个when守卫是一种反模式。

zip 中,您可以通过删除冗余防护来实现与zip'相同的效果:

let zip (series1: TimeSeries<float>) (series2: TimeSeries<float>) =
    let rec loop revAcc ser1 ser2 =
       match ser1, ser2 with
       | [], _ | _, [] -> List.rev revAcc
       | hd1::tl1, hd2::tl2 when hd1.Time = hd2.Time ->
           loop ({ Time = hd1.Time; Value = (hd1.Value, hd2.Value) }::revAcc) tl1 tl2
       | hd1::tl1, hd2::tl2 when hd1.Time < hd2.Time ->
           loop revAcc tl1 ser2
       | hd1::tl1, hd2::tl2 ->
           loop revAcc ser1 tl2
    loop [] series1 series2

这两个函数都是尾递归的,因为在递归调用loop之后没有额外的工作。

对于第一种情况,编译器只看到守卫,并且不够聪明,无法推理它们何时适用/不适用 - 您可以通过删除最后一个 where 守卫来解决此问题。

第二,我猜它是尾递归的,但在这些情况下最好的办法是使用一个大的输入列表进行测试,看看你是否不会崩溃

最新更新