SML和功能性编码风格 [英] SML and functional coding style

查看:106
本文介绍了SML和功能性编码风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始通过编程语言课程学习标准ML。



在第一个作业中,我尝试编写一个函数 is_older ,它接受两个日期并计算为 true false 。如果第一个参数是第二个参数之前的日期,那么它的计算结果为 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秒)然后假
否则如果(#1第一#1秒)然后是真
否则如果(#1第一=#1秒并且#2第一#2秒)则true
else if(#1 first =#1 second andalso#2 first =#2 second andalso#3 first##3 second)then true
else false

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



如何重写这个代码的功能风格是什么?

解决方案




  • 使用模式匹配来分解元组。

  • 使用布尔运算符( an当 if / else 构造返回布尔值时,dalso orelse

    $ b

    (*以(年,月,日)*)
    的形式比较两个日期fun is_older((y1,m1,d1),(y2,m2,d2))=
    y1< (y1 = y2且也是m1 orelse(y1 = y2并且也是m1 = m2并且也是d1


    I'm start to learn Standard ML with Programming languages course.

    In the first homework, I try to write a function is_older that takes two dates and evaluates to true or false. It evaluates to true if the first argument is a date that comes before the second argument (If the two dates are the same, the result is false.).

    So I write the following code:

    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
    

    The code is works fine, but it looks ugly.

    How can I rewrite this code in functional style?

    解决方案

    Two suggestions:

    • Use pattern matching to decompose tuples.
    • Use boolean operators (andalso, orelse, etc.) when if/else constructs return boolean.

    A more readable version:

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

    这篇关于SML和功能性编码风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆