【问题标题】:Haskell multiple conditions combinedHaskell 多个条件相结合
【发布时间】: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


【解决方案1】:

普通 Haskell 中的一些替代方案(无扩展):

  • if then else 链:

    if lapyear anyo then
       if or [...] then 31
       else if mes == 02 then 29
       else 30
    else ...
    
  • 使用let:

    if lapyear anyo then
       let result | or [...]  = 31
                  | mes == 02 = 29
                  | otherwise = 30
            in result
    else ...
    
  • 使用case:

    if lapyear anyo then
       case () of
       _ | or [...]  -> 31
         | mes == 02 -> 29
         | otherwise -> 30
    else ...
    

我相信最后一个是最受欢迎的。

【讨论】:

  • 对我来说似乎是最简单的方法,无需导入任何内容。谢谢!
【解决方案2】:

您可能会喜欢MultiWayIf 扩展。

{-# LANGUAGE MultiWayIf #-}

if lapyear anyo then if
    | or [...] -> 31
    | mes == 20 -> 29
    | otherwise -> 30
else if
    | ...

【讨论】:

  • 谢谢!我认为这会起作用,但现在出现一个错误,上面写着“多路 if 表达式需要 MultiWayIf 打开”。如何导入 multiwayif ?
  • 它现在可以工作了,我只需要 multiwayif 通过 :set -XMultiWayIf 再次感谢你
  • 注意{-# LANGUAGE MultiWayIf #-}。如果将其放在文件的最顶部,则不需要命令行标志。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多