有没有更加惯用的方式来对记录进行模式匹配?我的代码似乎不太对劲。
type Period = AM | PM
type TimeOfDay = {hours : int; minutes : int; p : Period}
let before (tod1 : TimeOfDay, tod2 : TimeOfDay) =
match tod1, tod2 with
| {hours = h1; minutes = m1; p = AM}, {hours = h2; minutes = m2; p = AM} -> (h1, m1) < (h2, m2)
| {hours = h1; minutes = m1; p = PM}, {hours = h2; minutes = m2; p = PM} -> (h1, m1) < (h2, m2)
| {hours = _; minutes = _; p = AM}, {hours = _; minutes = _; p = PM} -> true
| {hours = _; minutes = _; p = PM}, {hours = _; minutes = _; p = AM} -> false
Period
放到TimeOfDay
的首个字段,那么TimeOfDay
的值将按你期望的顺序自然排序,这样你就可以只使用tod1 < tod2
。这是因为在你对Period
的定义中,AM
位于PM
之前。虽然这对你的问题没有帮助。 - Leaf Garland(tod1.p, tod1.hours, tod1.minutes) < (tod2.p, tod2.hours, tod2.minutes)
进行比较。 - Tarmillet adjust = function | {hours=h; minutes=m; p=PM} -> {hours=h+12; minutes=m; p=AM} | x -> x
,然后比较应用此函数到两个记录的结果:let before (tod1, tod2) = adjust tod1 < adjust tod2
。 - Be Brave Be Like Ukraine