Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on records in F#

Tags:

idioms

f#

Is there a more idiomatic way how to do pattern matching on records? My code just doesn't seem right.

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
like image 987
prasopes Avatar asked Mar 22 '23 02:03

prasopes


1 Answers

You can do a slight improvement as you don't need to show unneeded patterns to produce the following

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)
   | { p = AM}, {p = PM} -> true
   | { p = PM}, {p = AM} -> false

Next, you could define an Active Pattern to deconstruct the type into a Tuple as follows

let (|TIME|) (t:TimeOfDay) = t.hours,t.minutes,t.p

let before (tod1 : TimeOfDay, tod2 : TimeOfDay) =
   match tod1, tod2 with
   | TIME(h1,m1,AM), TIME(h2,m2,PM) -> (h1, m1) < (h2, m2)
   | TIME(h1,m1,PM), TIME(h2,m2,PM) -> (h1, m1) < (h2, m2)
   | { p = AM}, {p = PM} -> true
   | { p = PM}, {p = AM} -> false
like image 85
John Palmer Avatar answered Mar 28 '23 01:03

John Palmer