【问题标题】:SML and functional coding styleSML 和函数式编码风格
【发布时间】:2013-01-17 07:50:38
【问题描述】:

我开始通过Programming languages 课程学习标准机器学习。

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

代码运行良好,但看起来很难看。

如何以函数式风格重写这段代码?

【问题讨论】:

    标签: functional-programming sml


    【解决方案1】:

    两个建议:

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

    更易读的版本:

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

    【讨论】:

      【解决方案2】:

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

      if b then
        true
      else
        false
      

      你应该只用b 交换它,因为它看起来是一样的。 pad 提供的解决方案可能也是我的解决方案,因为它又好又短。

      但是,当您最终得到那些讨厌的/嵌套的 if-then-else,并且您没有返回简单的东西(例如,true/false 或数字)时,那么您应该考虑使用 case。您的函数不是使用的主要候选者,但我希望下面仍然显示这个想法(您可以轻松地构建那些嵌套 if 的结构)

      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
      

      【讨论】:

        【解决方案3】:
        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)
        

        【讨论】:

        • 添加一些 cmets 将有助于其他人理解您的答案建议。
        猜你喜欢
        • 2017-08-20
        • 1970-01-01
        • 2013-01-13
        • 1970-01-01
        • 1970-01-01
        • 2019-01-14
        • 1970-01-01
        • 1970-01-01
        • 2016-01-11
        相关资源
        最近更新 更多