2013-01-17 39 views
6

我开始学习标准ML Programming languages当然。SML和功能性编码风格

在第一个作业中,我尝试编写一个函数is_older,该函数需要两个日期并且计算结果为truefalse。如果第一个参数是第二个参数之前的日期,则它的计算结果为true(如果两个日期相同,则结果为false。)。

所以我写了下面的代码:

fun is_older(first: int * int * int, second: int * int * int) = 
    if(#1 first = #1 second andalso #2 first = #2 second andalso #3 first = #3 second) then false 
    else if (#1 first < #1 second) then true 
    else if (#1 first = #1 second andalso #2 first < #2 second) then true 
    else if (#1 first = #1 second andalso #2 first = #2 second andalso #3 first < #3 second) then true 
    else false 

的代码工作正常,但它看起来丑陋。

如何以功能样式重写此代码?

回答

12

两个建议:

  • 使用模式匹配分解的元组。
  • if/else构造返回布尔值时,使用布尔运算符(andalso,orelse等)。

更可读的版本:

(* Compare two dates in the form of (year, month, day) *) 
fun is_older((y1, m1, d1), (y2, m2, d2)) = 
    y1 < y2 orelse (y1 = y2 andalso m1 < m2) 
    orelse (y1 = y2 andalso m1 = m2 andalso d1 < d2) 
9

一般来说,当你有表格上的东西

if b then 
    true 
else 
    false 

你应该只是b交流一下,因为它是平凡的看到是相同。 pad提供的解决方案可能也是我的解决方案,因为它很好,很短。然而,当你最终得到那些讨厌的/嵌套的if-then-else,并且你没有返回简单的东西(例如,true/false或数字)时,你应该考虑使用一个case。你的功能是不是总理候选人使用,但是我希望下面还是给出了这个概念(你可以轻松地让这些嵌套,如果公司的结构)

fun is_older((y1, m1, d1), (y2, m2, d2)) = 
    case (Int.compare(y1,y2), Int.compare(m1,m2), Int.compare(d1, d2)) of 
     (LESS , _ , _ ) => true 
    | (EQUAL, LESS , _ ) => true 
    | (EQUAL, EQUAL, LESS) => true 
    | _ => false 
1
fun is_older((yr1 : int , mo1 : int , dt1 : int), (yr2 : int , mo2 : int , dt2 : int)) = 
    yr1 < yr2 orelse (yr1 = yr2 andalso mo1 < mo2) 
    orelse (yr1 = yr2 andalso mo1 = mo2 andalso dt1 < dt2) 
+1

添加一些评论将帮助其他人了解你的答案propposal 。 – Yaroslav