我正在做一个练习,其中给出了两个时间戳,我必须找到哪个很大。这个程序是用SML编写的。所以我想出了这个程序......
type triple = {int,int,string};
val record1 = (11,45,"PM");
val record2 = (2,13,"AM");
fun timerrecord(record1:triple,record2:triple)=
let val (hour1:int,min1:int,f1:string) = record1;
val (hour2:int,min2:int,f2:string) = record2
in
if (f1= "AM") andalso (f2="PM") then "t1 comes First"
else if(f1 = "PM") andalso (f2="AM") then "t2 comes First"
else if (hour1 < hour2) then "t1 comes First"
else if (hour1 > hour2) then "t2 comes First"
else if (min1 < min2) then "t1 comes First"
else "t2 comes First";
上面的程序并没有作为一个整体执行,但个别逻辑是因为元组。我无法充分利用元组来比较2个时间戳。 此外,我想知道如何获取元组,就好像它已知,然后我们可以轻松解决这个问题。 提前谢谢。
答案 0 :(得分:1)
我想你的意思是
type triple = (int*int*string)
另外,你应该避免;
,它们只在REPL中是必需的。而且您忘记在函数正文中end
表达式的末尾添加let..in..end
。还要避免使用;
或者它不会编译(至少不能在我的SML版本中)。
你的问题并不完全清楚,我很确定有很多方法可以做到这一点。或者你可以尝试一下:
fun timerrecord(record1:triple,record2:triple)=
case (record1, record2) of
((_,_,"AM"),(_,_,"PM")) => record1
| ((_,_,"PM"),(_,_,"AM")) => record2
| ((h1,m1,_),(h2,m2,_)) => if h1 < h2 then record1
else if h2 < h1 then record2
else if m1 < m2 then record1
else record2
答案 1 :(得分:1)
有几种方法可以做到这一点。您可以定义记录类型以编译此函数:
type recc = {hour:int, min:int, f:string};
并将您的功能签名更改为:
fun timerrecord(record1:recc,record2:recc)=
或者您可以通过将功能签名更改为:
fun timerrecord(record1:{hour:int, min:int, f:string},record2:{hour:int, min:int, f:string})=
ML是通过模式匹配来实现的:
fun timerRecord({hour = h1, min = m1, f = f1}, {hour = h2, min = m2, f = f2}) =
你的功能将是:
fun timerRecord({hour = h1, min = m1, f = f1}, {hour = h2, min = m2, f = f2}) =
if (f1= "AM") andalso (f2="PM") then "t1 comes First"
else if(f1 = "PM") andalso (f2="AM") then "t2 comes First"
else if (h1 < h2) then "t1 comes First"
else if (h1 > h2) then "t2 comes First"
else if (m1 < m2) then "t1 comes First"
else "t2 comes First";