【发布时间】:2016-02-04 05:29:15
【问题描述】:
我一直在寻找一段时间,但没有找到我的问题的任何答案。 我试图编写一个函数,根据它是否在一圈内返回特定月份的天数。我之前已经定义了函数“lapyear”。我的问题是如何在另一个 If 条件中创建一个 If 条件?
非常感谢您的回答:)
lapyear:: Int->Bool
lapyear a
|((rem)a 400)==0 = True
|((rem)a 100)==0 = False
|((rem)a 4)==0 = True
|otherwise = False
type Mes = Int
type Anyo = Int
type Dias= Int
daysAmonth:: Mes->Anyo->Dias
daysAmonth mes anyo
if lapyear anyo then do
|or[mes==01,mes==03,mes==05,mes==07,mes==08,mes==10,mes==12] = 31
|mes==02 = 29
|otherwise = 30
else
|or[mes==01,mes==03,mes==05,mes==07,mes==08,mes==10,mes==12] = 31
|mes==02 = 28
|otherwise = 30
【问题讨论】:
-
if <cond1> then if <cond2> then x1 else x2 else x3?或者您可能对 GHC 的MultiWayIf扩展感兴趣。 -
无论如何代码似乎是错误的。你有
mes == [01, 03, ..],然后是mes == 02。但列表不太可能是Num实例,因此这可能会引发类型错误。 -
我希望程序首先检查 lapyear anyo 的条件,然后根据该条件继续检查其他三个条件
-
为了让你的 ifs 更清晰一些,考虑使用 Haskell 类型系统将你的 Mes 定义为数据类型而不是 Int: data Mes = enero |费布雷罗 |马佐 | ... |十一月 | diciembre 还考虑限制您的 Dias 数据类型,如:stackoverflow.com/questions/7302735/… 中所建议的那样
-
在不相关的注释上,您可能想重写 lapyear like so
标签: function haskell if-statement conditional-statements