You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell函数问题:如何根据闰年条件修改二月的返回天数

解决Haskell days函数的实现问题

你的代码存在语法错误,Haskell的模式匹配和条件判断逻辑写法不符合语法规范,下面是两种正确的实现方式:

方式一:模式匹配+守卫

这种写法更贴合Haskell的函数式风格,针对每个月份做模式匹配,2月通过守卫判断闰年:

days :: Int -> Int -> Int
days 1 _ = 31
days 2 year
  | ily year = 29
  | otherwise = 28
days 3 _ = 31
days 4 _ = 30
days 5 _ = 31
days 6 _ = 30
days 7 _ = 31
days 8 _ = 31
days 9 _ = 30
days 10 _ = 31
days 11 _ = 30
days 12 _ = 31
-- 可选:处理无效月份的情况
days _ _ = error "Invalid month (must be 1-12)"

方式二:case表达式

如果更习惯集中式的分支判断,可以用case表达式实现:

days :: Int -> Int -> Int
days month year = case month of
  1 -> 31
  2 -> if ily year then 29 else 28
  3 -> 31
  4 -> 30
  5 -> 31
  6 -> 30
  7 -> 31
  8 -> 31
  9 -> 30
  10 -> 31
  11 -> 30
  12 -> 31
  _ -> error "Month must be between 1 and 12"

原代码的问题说明

  • 模式匹配语法错误:month 1不是正确的匹配写法,Haskell需要直接指定参数值,比如days 1 year表示第一个参数(月份)为1的情况。
  • 条件判断逻辑错误:不能在模式匹配分支中直接写if ... then month 2 = ...,需将2月的逻辑单独作为分支,通过守卫或if表达式返回对应天数。

这两种实现都能满足需求:针对2月通过闰年判断返回不同天数,其他月份返回固定天数。

内容的提问来源于stack exchange,提问作者Bailey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:18:17