0

我正在做一个练习,其中给出了两个时间戳,我必须找到哪个大。这个程序是用 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 个时间戳。另外我想知道如何访问元组,就好像它是已知的那样我们可以很容易地解决这个问题。提前致谢。

4

2 回答 2

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";
于 2013-11-14T20:50:19.650 回答
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
于 2013-11-14T20:41:03.150 回答