我开始学习标准机器学习编程语言 https://www.coursera.org/course/proglang course.
在第一个作业中,我尝试编写一个函数is_older
需要两个日期并评估为true
or 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 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
该代码工作正常,但看起来很丑。
如何以函数式风格重写这段代码?
两个建议:
- 使用模式匹配来分解元组。
- 使用布尔运算符 (
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)