【问题标题】:SML program and tupleSML 程序和元组
【发布时间】:2013-11-15 05:49:42
【问题描述】:

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

【问题讨论】:

    标签: tuples sml


    【解决方案1】:

    我猜你是说

    type triple = (int*int*string)
    

    此外,您应该避免使用;,它们仅在 REPL 中是必需的。而且您忘记在函数体中 let..in..end 表达式的末尾添加 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
    

    【讨论】:

    • 感谢@Edwin Dalorzo 的解释并找出我的错误。在某处我读到元组是有序记录所以我以“记录方式”写元组(我的错误)!!!其次,我想问一下如何访问元组中的元素。我的意思是像'#n r'在记录中。在sml中有元组的东西吗?
    • 是一样的,你只需要使用数字而不是字段名(即#1 record1#2 record1
    【解决方案2】:

    有几种方法可以做到这一点。您可以定义记录类型以编译此函数:

    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";
    

    【讨论】:

    • 谢谢@user987339。实际上我之前已经阅读了您对“用于比较时间戳的SML程序”问题的回答,所以我有了一个使用元组实现它的想法。
    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2012-04-02
    • 2018-08-13
    相关资源
    最近更新 更多