SML和功能编码风格

时间:2013-01-17 07:50:39

标签: functional-programming sml

我开始用Programming languages课程学习标准ML。

在第一个作业中,我尝试编写一个函数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

代码工作正常,但看起来很难看。

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

3 个答案:

答案 0 :(得分:13)

两个建议:

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

更易阅读的版本:

(* 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)

答案 1 :(得分:9)

一般情况下,表格上有内容

if b then
  true
else
  false

你应该只与b交换它,因为它看起来很平常。 pad提供的解决方案可能也是我的解决方案,因为它很好而且简短。

然而,当你最终得到那些令人讨厌/嵌套的if-then-else,并且你没有返回简单的东西(例如,真/假或数字)时,你应该考虑使用一个案例。你的函数不是一个主要的候选者,但我希望下面的内容仍然显示出来(你可以轻松地制作那些嵌套的结构)

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

答案 2 :(得分: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)