Sml 我的功能有什么问题
我有一个函数,如果传递的参数是一个合理的日期,它应该返回true,否则返回false。问题是,即使在明显合理的日期,它也返回false,我无法找出它的错误。眼睛更锐利的人请帮忙。这是:Sml 我的功能有什么问题,sml,smlnj,Sml,Smlnj,我有一个函数,如果传递的参数是一个合理的日期,它应该返回true,否则返回false。问题是,即使在明显合理的日期,它也返回false,我无法找出它的错误。眼睛更锐利的人请帮忙。这是: fun reasonable_date(x: int*int*int) = if #1 x > 0 andalso #2 x > 0 andalso #2 x <= 12 andalso #3 x > 0 andalso #3 x <= 31 then
fun reasonable_date(x: int*int*int) =
if #1 x > 0 andalso #2 x > 0 andalso #2 x <= 12 andalso #3 x > 0 andalso #3 x <= 31
then
if #2 x = 1 mod 2 andalso #2 x < 8 andalso #3 x <= 31 then true
else if #2 x = 0 mod 2 andalso #2 x >= 8 andalso #3 x <= 31
then true
else if #2 x = 0 mod 2 andalso #2 x < 8
then
if #2 x = 2 andalso (#3 x = 28 orelse #3 x = 29) then true
else if #2 x = 0 mod 2 andalso #3 x <= 30 then true
else false
else if #2 x = 1 mod 2 andalso #2 x > 8 andalso #3 x <=30 then true
else false
else false
日期(x:int*int*int)=
如果#1x>0 andalso#2x>0 andalso#2x0 andalso#3x您可以重复使用诸如〈代码〉如果#2x=1 mod 2〈代码〉之类的条件。这几乎可以肯定并不像你想象的那样有效。这里,
mod
是一个算术运算符,表示1除以2时得到的余数,而不是表示#2x
等于1模2的数学表达式。因此,与其测试#2x
是否为奇数,不如测试它是否等于1。根据您的条件,您实际上只允许在#2x
为1时使用true
,因此您的合理日期必须全部在1月份(甚至可能没有,我还没有处理所有条件) 您当前的解决方案无法维护,其逻辑看起来像是地狱般的:)
我建议您将其分解为更小的逻辑部分,以确保简单的属性。因此,不必首先测试年、月和日是否大于或等于一,您可以将关于年、月和日的所有逻辑分组
fun daysInMonth n =
List.nth([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], n-1)
fun reasonable_date (y, m, d) =
(* Check year >= 1 *)
y >= 1 andalso
(* Check 1 <= month <= 12 *)
(m >= 1 andalso m <= 12) andalso
(* Check 1 <= day <= n, for n being the number of days in specified month *)
(d >= 1 andalso d <= daysInMonth m)
乐趣日每月n=
列表n([31,28,31,30,31,30,30,31,31,30,31,30,31],n-1)
日期(y、m、d)=
(*检查年份>=1*)
y>=1,并且
(*勾选1我更喜欢这个看起来更可读的解决方案
fun reasonable_date (y, m, d) =
let val daysInMonth =
List.nth([31, if isLeapYear y then 29 else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], m-1)
in
(* Check year >= 1 *)
y >= 1 andalso
(* Check 1 <= month <= 12 *)
(m >= 1 andalso m <= 12) andalso
(* Check 1 <= day <= n, for n being the number of days in specified month *)
(d >= 1 andalso d <= daysInMonth)
end
日期(y、m、d)=
让瓦尔一天一个月=
列表n([31,如果是一年,则为29,否则为28、31、30、31、30、31、30、31、31、31、31、31、m-1)
在里面
(*检查年份>=1*)
y>=1,并且
(*检查1)是否意味着它总是返回false,或者它返回一些假,但不是全部,合理的日期?您可以考虑替换一些<代码>如果是“否则”< /COD>表达式具有适当的<代码>,也可以是或“代码> ORE < /代码>。这是一个相当复杂的问题,目前它总是返回false。但是现在没问题。它是F。伊克塞德。谢谢汉克斯,这很有用。:)它已经修好了,现在我要对它进行改造以应对闰年:)
fun reasonable_date (y, m, d) =
let val daysInMonth =
List.nth([31, if isLeapYear y then 29 else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], m-1)
in
(* Check year >= 1 *)
y >= 1 andalso
(* Check 1 <= month <= 12 *)
(m >= 1 andalso m <= 12) andalso
(* Check 1 <= day <= n, for n being the number of days in specified month *)
(d >= 1 andalso d <= daysInMonth)
end