SML和功能编码风格

Joh*_*tin 6 functional-programming sml

我开始学习标准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
Run Code Online (Sandbox Code Playgroud)

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

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

pad*_*pad 13

两个建议:

  • 使用模式匹配来分解元组.
  • 在构造返回布尔值时使用布尔运算符(andalso,orelse等)if/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)
Run Code Online (Sandbox Code Playgroud)


Jes*_*erg 9

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

if b then
  true
else
  false
Run Code Online (Sandbox Code Playgroud)

你应该只是交换它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
Run Code Online (Sandbox Code Playgroud)